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 2025/03/21 15:07:50 UTC
(kafka) branch trunk updated: KAFKA-18329; [3/3] Delete old group coordinator (KIP-848) (#19255)
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 ca20e9cd92f KAFKA-18329; [3/3] Delete old group coordinator (KIP-848) (#19255)
ca20e9cd92f is described below
commit ca20e9cd92f923c29d71c6fa554ea553b0109b33
Author: David Jacot <da...@gmail.com>
AuthorDate: Fri Mar 21 16:07:42 2025 +0100
KAFKA-18329; [3/3] Delete old group coordinator (KIP-848) (#19255)
This patch is the third of a series of patches to remove the old group
coordinator. With the release of Apache Kafka 4.0, the so-called new
group coordinator is the default and only option available now.
It removes the old group coordinator and cleans up the
`GroupCoordinator` interface.
Reviewers: Jeff Kim <je...@confluent.io>, Chia-Ping Tsai <ch...@gmail.com>
---
.../kafka/coordinator/group/DelayedHeartbeat.scala | 36 -
.../kafka/coordinator/group/DelayedJoin.scala | 94 -
.../kafka/coordinator/group/DelayedRebalance.scala | 33 -
.../kafka/coordinator/group/DelayedSync.scala | 48 -
.../kafka/coordinator/group/GroupCoordinator.scala | 1872 ---------
.../group/GroupCoordinatorAdapter.scala | 690 ----
.../kafka/coordinator/group/GroupMetadata.scala | 857 ----
.../coordinator/group/GroupMetadataManager.scala | 1290 ------
.../kafka/coordinator/group/MemberMetadata.scala | 153 -
.../group/GroupCoordinatorAdapterTest.scala | 987 -----
.../group/GroupCoordinatorConcurrencyTest.scala | 406 --
.../coordinator/group/GroupCoordinatorTest.scala | 4249 --------------------
.../group/GroupMetadataManagerTest.scala | 3122 --------------
.../coordinator/group/GroupMetadataTest.scala | 866 ----
.../coordinator/group/MemberMetadataTest.scala | 94 -
.../scala/unit/kafka/server/KafkaApisTest.scala | 2 +-
.../kafka/coordinator/group/GroupCoordinator.java | 20 -
.../coordinator/group/GroupCoordinatorService.java | 13 -
18 files changed, 1 insertion(+), 14831 deletions(-)
diff --git a/core/src/main/scala/kafka/coordinator/group/DelayedHeartbeat.scala b/core/src/main/scala/kafka/coordinator/group/DelayedHeartbeat.scala
deleted file mode 100644
index 1dd2793c553..00000000000
--- a/core/src/main/scala/kafka/coordinator/group/DelayedHeartbeat.scala
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * 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 kafka.coordinator.group
-
-import org.apache.kafka.server.purgatory.DelayedOperation
-
-/**
- * Delayed heartbeat operations that are added to the purgatory for session timeout checking.
- * Heartbeats are paused during rebalance.
- */
-private[group] class DelayedHeartbeat(coordinator: GroupCoordinator,
- group: GroupMetadata,
- memberId: String,
- isPending: Boolean,
- timeoutMs: Long)
- extends DelayedOperation(timeoutMs, group.lock) {
-
- override def tryComplete(): Boolean = coordinator.tryCompleteHeartbeat(group, memberId, isPending, forceComplete _)
- override def onExpiration(): Unit = coordinator.onExpireHeartbeat(group, memberId, isPending)
- override def onComplete(): Unit = {}
-}
diff --git a/core/src/main/scala/kafka/coordinator/group/DelayedJoin.scala b/core/src/main/scala/kafka/coordinator/group/DelayedJoin.scala
deleted file mode 100644
index 51eeb324b1c..00000000000
--- a/core/src/main/scala/kafka/coordinator/group/DelayedJoin.scala
+++ /dev/null
@@ -1,94 +0,0 @@
-/**
- * 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 kafka.coordinator.group
-
-import org.apache.kafka.server.purgatory.{DelayedOperationPurgatory, GroupJoinKey}
-import java.util
-import scala.math.{max, min}
-
-/**
- * Delayed rebalance operations that are added to the purgatory when group is preparing for rebalance
- *
- * Whenever a join-group request is received, check if all known group members have requested
- * to re-join the group; if yes, complete this operation to proceed rebalance.
- *
- * When the operation has expired, any known members that have not requested to re-join
- * the group are marked as failed, and complete this operation to proceed rebalance with
- * the rest of the group.
- */
-private[group] class DelayedJoin(
- coordinator: GroupCoordinator,
- group: GroupMetadata,
- rebalanceTimeout: Long
-) extends DelayedRebalance(
- rebalanceTimeout,
- group.lock
-) {
- override def tryComplete(): Boolean = coordinator.tryCompleteJoin(group, forceComplete _)
-
- override def onExpiration(): Unit = {
- // try to complete delayed actions introduced by coordinator.onCompleteJoin
- tryToCompleteDelayedAction()
- }
- override def onComplete(): Unit = coordinator.onCompleteJoin(group)
-
- // TODO: remove this ugly chain after we move the action queue to handler thread
- private def tryToCompleteDelayedAction(): Unit = coordinator.groupManager.replicaManager.tryCompleteActions()
-}
-
-/**
- * Delayed rebalance operation that is added to the purgatory when a group is transitioning from
- * Empty to PreparingRebalance
- *
- * When onComplete is triggered we check if any new members have been added and if there is still time remaining
- * before the rebalance timeout. If both are true we then schedule a further delay. Otherwise we complete the
- * rebalance.
- */
-private[group] class InitialDelayedJoin(
- coordinator: GroupCoordinator,
- purgatory: DelayedOperationPurgatory[DelayedRebalance],
- group: GroupMetadata,
- configuredRebalanceDelay: Int,
- delayMs: Int,
- remainingMs: Int
-) extends DelayedJoin(
- coordinator,
- group,
- delayMs
-) {
- override def tryComplete(): Boolean = false
-
- override def onComplete(): Unit = {
- group.inLock {
- if (group.newMemberAdded && remainingMs != 0) {
- group.newMemberAdded = false
- val delay = min(configuredRebalanceDelay, remainingMs)
- val remaining = max(remainingMs - delayMs, 0)
- purgatory.tryCompleteElseWatch(new InitialDelayedJoin(coordinator,
- purgatory,
- group,
- configuredRebalanceDelay,
- delay,
- remaining
- ), util.List.of(new GroupJoinKey(group.groupId)))
- } else
- super.onComplete()
- }
- }
-
-}
diff --git a/core/src/main/scala/kafka/coordinator/group/DelayedRebalance.scala b/core/src/main/scala/kafka/coordinator/group/DelayedRebalance.scala
deleted file mode 100644
index 2c327b922eb..00000000000
--- a/core/src/main/scala/kafka/coordinator/group/DelayedRebalance.scala
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * 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 kafka.coordinator.group
-
-import org.apache.kafka.server.purgatory.DelayedOperation
-import java.util.concurrent.locks.Lock
-
-/**
- * Delayed rebalance operation that is shared by DelayedJoin and DelayedSync
- * operations. This allows us to use a common purgatory for both cases.
- */
-private[group] abstract class DelayedRebalance(
- rebalanceTimeoutMs: Long,
- groupLock: Lock
-) extends DelayedOperation(
- rebalanceTimeoutMs,
- groupLock
-)
diff --git a/core/src/main/scala/kafka/coordinator/group/DelayedSync.scala b/core/src/main/scala/kafka/coordinator/group/DelayedSync.scala
deleted file mode 100644
index a39adefe3aa..00000000000
--- a/core/src/main/scala/kafka/coordinator/group/DelayedSync.scala
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * 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 kafka.coordinator.group
-
-/**
- * Delayed rebalance operation that is added to the purgatory when the group is completing the
- * rebalance.
- *
- * Whenever a SyncGroup is received, checks that we received all the SyncGroup request from
- * each member of the group; if yes, complete this operation.
- *
- * When the operation has expired, any known members that have not sent a SyncGroup requests
- * are removed from the group. If any members is removed, the group is rebalanced.
- */
-private[group] class DelayedSync(
- coordinator: GroupCoordinator,
- group: GroupMetadata,
- generationId: Int,
- rebalanceTimeoutMs: Long
-) extends DelayedRebalance(
- rebalanceTimeoutMs,
- group.lock
-) {
- override def tryComplete(): Boolean = {
- coordinator.tryCompletePendingSync(group, generationId, forceComplete _)
- }
-
- override def onExpiration(): Unit = {
- coordinator.onExpirePendingSync(group, generationId)
- }
-
- override def onComplete(): Unit = { }
-}
diff --git a/core/src/main/scala/kafka/coordinator/group/GroupCoordinator.scala b/core/src/main/scala/kafka/coordinator/group/GroupCoordinator.scala
deleted file mode 100644
index bf2f3874314..00000000000
--- a/core/src/main/scala/kafka/coordinator/group/GroupCoordinator.scala
+++ /dev/null
@@ -1,1872 +0,0 @@
-/**
- * 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 kafka.coordinator.group
-
-import java.util
-import java.util.{OptionalInt, Properties}
-import java.util.concurrent.atomic.AtomicBoolean
-import kafka.server._
-import kafka.utils.Logging
-import org.apache.kafka.common.{TopicIdPartition, TopicPartition}
-import org.apache.kafka.common.config.TopicConfig
-import org.apache.kafka.common.internals.Topic
-import org.apache.kafka.common.message.JoinGroupResponseData.JoinGroupResponseMember
-import org.apache.kafka.common.message.LeaveGroupRequestData.MemberIdentity
-import org.apache.kafka.common.metrics.Metrics
-import org.apache.kafka.common.metrics.stats.Meter
-import org.apache.kafka.common.protocol.{ApiKeys, Errors}
-import org.apache.kafka.common.record.RecordBatch
-import org.apache.kafka.common.requests._
-import org.apache.kafka.common.utils.Time
-import org.apache.kafka.coordinator.group.{Group, OffsetAndMetadata, OffsetConfig}
-import org.apache.kafka.server.common.RequestLocal
-import org.apache.kafka.server.purgatory.{DelayedOperationPurgatory, GroupJoinKey, GroupSyncKey, MemberKey}
-import org.apache.kafka.server.record.BrokerCompressionType
-import org.apache.kafka.storage.internals.log.VerificationGuard
-
-import java.util.concurrent.CompletableFuture
-import scala.collection.{Map, Seq, Set, immutable, mutable}
-import scala.math.max
-
-/**
- * GroupCoordinator handles general group membership and offset management.
- *
- * Each Kafka server instantiates a coordinator which is responsible for a set of
- * groups. Groups are assigned to coordinators based on their group names.
- * <p>
- * <b>Delayed operation locking notes:</b>
- * Delayed operations in GroupCoordinator use `group` as the delayed operation
- * lock. ReplicaManager.appendRecords may be invoked while holding the group lock
- * used by its callback. The delayed callback may acquire the group lock
- * since the delayed operation is completed only if the group lock can be acquired.
- */
-private[group] class GroupCoordinator(
- val brokerId: Int,
- val groupConfig: GroupConfig,
- val offsetConfig: OffsetConfig,
- val groupManager: GroupMetadataManager,
- val heartbeatPurgatory: DelayedOperationPurgatory[DelayedHeartbeat],
- val rebalancePurgatory: DelayedOperationPurgatory[DelayedRebalance],
- time: Time,
- metrics: Metrics
-) extends Logging {
- import GroupCoordinator._
-
- type JoinCallback = JoinGroupResult => Unit
- type SyncCallback = SyncGroupResult => Unit
-
- /* setup metrics */
- val offsetDeletionSensor = metrics.sensor("OffsetDeletions")
-
- offsetDeletionSensor.add(new Meter(
- metrics.metricName("offset-deletion-rate",
- "group-coordinator-metrics",
- "The rate of administrative deleted offsets"),
- metrics.metricName("offset-deletion-count",
- "group-coordinator-metrics",
- "The total number of administrative deleted offsets")))
-
- val groupCompletedRebalanceSensor = metrics.sensor("CompletedRebalances")
-
- groupCompletedRebalanceSensor.add(new Meter(
- metrics.metricName("group-completed-rebalance-rate",
- "group-coordinator-metrics",
- "The rate of completed rebalance"),
- metrics.metricName("group-completed-rebalance-count",
- "group-coordinator-metrics",
- "The total number of completed rebalance")))
-
- this.logIdent = "[GroupCoordinator " + brokerId + "]: "
-
- private val isActive = new AtomicBoolean(false)
-
- def offsetsTopicConfigs: Properties = {
- val props = new Properties
- props.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT)
- props.put(TopicConfig.SEGMENT_BYTES_CONFIG, offsetConfig.offsetsTopicSegmentBytes.toString)
- props.put(TopicConfig.COMPRESSION_TYPE_CONFIG, BrokerCompressionType.PRODUCER.name)
-
- props
- }
-
- /**
- * NOTE: If a group lock and metadataLock are simultaneously needed,
- * be sure to acquire the group lock before metadataLock to prevent deadlock
- */
-
- /**
- * Startup logic executed at the same time when the server starts up.
- */
- def startup(retrieveGroupMetadataTopicPartitionCount: () => Int, enableMetadataExpiration: Boolean = true): Unit = {
- info("Starting up.")
- groupManager.startup(retrieveGroupMetadataTopicPartitionCount, enableMetadataExpiration)
- isActive.set(true)
- info("Startup complete.")
- }
-
- /**
- * Shutdown logic executed at the same time when server shuts down.
- * Ordering of actions should be reversed from the startup process.
- */
- def shutdown(): Unit = {
- info("Shutting down.")
- isActive.set(false)
- groupManager.shutdown()
- heartbeatPurgatory.shutdown()
- rebalancePurgatory.shutdown()
- info("Shutdown complete.")
- }
-
- /**
- * Verify if the group has space to accept the joining member. The various
- * criteria are explained below.
- */
- private def acceptJoiningMember(group: GroupMetadata, member: String): Boolean = {
- group.currentState match {
- // Always accept the request when the group is empty or dead
- case Empty | Dead =>
- true
-
- // An existing member is accepted if it is already awaiting. New members are accepted
- // up to the max group size. Note that the number of awaiting members is used here
- // for two reasons:
- // 1) the group size is not reliable as it could already be above the max group size
- // if the max group size was reduced.
- // 2) using the number of awaiting members allows to kick out the last rejoining
- // members of the group.
- case PreparingRebalance =>
- (group.has(member) && group.get(member).isAwaitingJoin) ||
- group.numAwaiting < groupConfig.groupMaxSize
-
- // An existing member is accepted. New members are accepted up to the max group size.
- // Note that the group size is used here. When the group transitions to CompletingRebalance,
- // members which haven't rejoined are removed.
- case CompletingRebalance | Stable =>
- group.has(member) || group.size < groupConfig.groupMaxSize
- }
- }
-
- def handleJoinGroup(groupId: String,
- memberId: String,
- groupInstanceId: Option[String],
- requireKnownMemberId: Boolean,
- supportSkippingAssignment: Boolean,
- clientId: String,
- clientHost: String,
- rebalanceTimeoutMs: Int,
- sessionTimeoutMs: Int,
- protocolType: String,
- protocols: List[(String, Array[Byte])],
- responseCallback: JoinCallback,
- reason: Option[String] = None,
- requestLocal: RequestLocal = RequestLocal.noCaching): Unit = {
- validateGroupStatus(groupId, ApiKeys.JOIN_GROUP).foreach { error =>
- responseCallback(JoinGroupResult(memberId, error))
- return
- }
-
- if (sessionTimeoutMs < groupConfig.groupMinSessionTimeoutMs ||
- sessionTimeoutMs > groupConfig.groupMaxSessionTimeoutMs) {
- responseCallback(JoinGroupResult(memberId, Errors.INVALID_SESSION_TIMEOUT))
- } else {
- val isUnknownMember = memberId == JoinGroupRequest.UNKNOWN_MEMBER_ID
- // group is created if it does not exist and the member id is UNKNOWN. if member
- // is specified but group does not exist, request is rejected with UNKNOWN_MEMBER_ID
- groupManager.getOrMaybeCreateGroup(groupId, isUnknownMember) match {
- case None =>
- responseCallback(JoinGroupResult(memberId, Errors.UNKNOWN_MEMBER_ID))
- case Some(group) =>
- group.inLock {
- val joinReason = reason.getOrElse("not provided")
- if (!acceptJoiningMember(group, memberId)) {
- group.remove(memberId)
- responseCallback(JoinGroupResult(JoinGroupRequest.UNKNOWN_MEMBER_ID, Errors.GROUP_MAX_SIZE_REACHED))
- } else if (isUnknownMember) {
- doNewMemberJoinGroup(
- group,
- groupInstanceId,
- requireKnownMemberId,
- supportSkippingAssignment,
- clientId,
- clientHost,
- rebalanceTimeoutMs,
- sessionTimeoutMs,
- protocolType,
- protocols,
- responseCallback,
- requestLocal,
- joinReason
- )
- } else {
- doCurrentMemberJoinGroup(
- group,
- memberId,
- groupInstanceId,
- clientId,
- clientHost,
- rebalanceTimeoutMs,
- sessionTimeoutMs,
- protocolType,
- protocols,
- responseCallback,
- joinReason
- )
- }
-
- // attempt to complete JoinGroup
- if (group.is(PreparingRebalance)) {
- rebalancePurgatory.checkAndComplete(new GroupJoinKey(group.groupId))
- }
- }
- }
- }
- }
-
- private def doNewMemberJoinGroup(
- group: GroupMetadata,
- groupInstanceId: Option[String],
- requireKnownMemberId: Boolean,
- supportSkippingAssignment: Boolean,
- clientId: String,
- clientHost: String,
- rebalanceTimeoutMs: Int,
- sessionTimeoutMs: Int,
- protocolType: String,
- protocols: List[(String, Array[Byte])],
- responseCallback: JoinCallback,
- requestLocal: RequestLocal,
- reason: String
- ): Unit = {
- group.inLock {
- if (group.is(Dead)) {
- // if the group is marked as dead, it means some other thread has just removed the group
- // from the coordinator metadata; it is likely that the group has migrated to some other
- // coordinator OR the group is in a transient unstable phase. Let the member retry
- // finding the correct coordinator and rejoin.
- responseCallback(JoinGroupResult(JoinGroupRequest.UNKNOWN_MEMBER_ID, Errors.COORDINATOR_NOT_AVAILABLE))
- } else if (!group.supportsProtocols(protocolType, MemberMetadata.plainProtocolSet(protocols))) {
- responseCallback(JoinGroupResult(JoinGroupRequest.UNKNOWN_MEMBER_ID, Errors.INCONSISTENT_GROUP_PROTOCOL))
- } else {
- val newMemberId = group.generateMemberId(clientId, groupInstanceId)
- groupInstanceId match {
- case Some(instanceId) =>
- doStaticNewMemberJoinGroup(
- group,
- instanceId,
- newMemberId,
- clientId,
- clientHost,
- supportSkippingAssignment,
- rebalanceTimeoutMs,
- sessionTimeoutMs,
- protocolType,
- protocols,
- responseCallback,
- requestLocal,
- reason
- )
- case None =>
- doDynamicNewMemberJoinGroup(
- group,
- requireKnownMemberId,
- newMemberId,
- clientId,
- clientHost,
- rebalanceTimeoutMs,
- sessionTimeoutMs,
- protocolType,
- protocols,
- responseCallback,
- reason
- )
- }
- }
- }
- }
-
- private def doStaticNewMemberJoinGroup(
- group: GroupMetadata,
- groupInstanceId: String,
- newMemberId: String,
- clientId: String,
- clientHost: String,
- supportSkippingAssignment: Boolean,
- rebalanceTimeoutMs: Int,
- sessionTimeoutMs: Int,
- protocolType: String,
- protocols: List[(String, Array[Byte])],
- responseCallback: JoinCallback,
- requestLocal: RequestLocal,
- reason: String
- ): Unit = {
- group.currentStaticMemberId(groupInstanceId) match {
- case Some(oldMemberId) =>
- info(s"Static member with groupInstanceId=$groupInstanceId and unknown member id joins " +
- s"group ${group.groupId} in ${group.currentState} state. Replacing previously mapped " +
- s"member $oldMemberId with this groupInstanceId.")
- updateStaticMemberAndRebalance(
- group,
- oldMemberId,
- newMemberId,
- groupInstanceId,
- protocols,
- rebalanceTimeoutMs,
- sessionTimeoutMs,
- responseCallback,
- requestLocal,
- reason,
- supportSkippingAssignment
- )
-
- case None =>
- info(s"Static member with groupInstanceId=$groupInstanceId and unknown member id joins " +
- s"group ${group.groupId} in ${group.currentState} state. Created a new member id $newMemberId " +
- s"for this member and add to the group.")
- addMemberAndRebalance(rebalanceTimeoutMs, sessionTimeoutMs, newMemberId, Some(groupInstanceId),
- clientId, clientHost, protocolType, protocols, group, responseCallback, reason)
- }
- }
-
- private def doDynamicNewMemberJoinGroup(
- group: GroupMetadata,
- requireKnownMemberId: Boolean,
- newMemberId: String,
- clientId: String,
- clientHost: String,
- rebalanceTimeoutMs: Int,
- sessionTimeoutMs: Int,
- protocolType: String,
- protocols: List[(String, Array[Byte])],
- responseCallback: JoinCallback,
- reason: String
- ): Unit = {
- if (requireKnownMemberId) {
- // If member id required, register the member in the pending member list and send
- // back a response to call for another join group request with allocated member id.
- info(s"Dynamic member with unknown member id joins group ${group.groupId} in " +
- s"${group.currentState} state. Created a new member id $newMemberId and request the " +
- s"member to rejoin with this id.")
- group.addPendingMember(newMemberId)
- addPendingMemberExpiration(group, newMemberId, sessionTimeoutMs)
- responseCallback(JoinGroupResult(newMemberId, Errors.MEMBER_ID_REQUIRED))
- } else {
- info(s"Dynamic Member with unknown member id joins group ${group.groupId} in " +
- s"${group.currentState} state. Created a new member id $newMemberId for this member " +
- s"and add to the group.")
- addMemberAndRebalance(rebalanceTimeoutMs, sessionTimeoutMs, newMemberId, None,
- clientId, clientHost, protocolType, protocols, group, responseCallback, reason)
- }
- }
-
- private def validateCurrentMember(
- group: GroupMetadata,
- memberId: String,
- groupInstanceId: Option[String],
- operation: String
- ): Option[Errors] = {
- // We are validating two things:
- // 1. If `groupInstanceId` is present, then it exists and is mapped to `memberId`
- // 2. The `memberId` exists in the group
- groupInstanceId.flatMap { instanceId =>
- group.currentStaticMemberId(instanceId) match {
- case Some(currentMemberId) if currentMemberId != memberId =>
- info(s"Request memberId=$memberId for static member with groupInstanceId=$instanceId " +
- s"is fenced by current memberId=$currentMemberId during operation $operation")
- Some(Errors.FENCED_INSTANCE_ID)
- case Some(_) =>
- None
- case None =>
- Some(Errors.UNKNOWN_MEMBER_ID)
- }
- }.orElse {
- if (!group.has(memberId)) {
- Some(Errors.UNKNOWN_MEMBER_ID)
- } else {
- None
- }
- }
- }
-
- private def doCurrentMemberJoinGroup(
- group: GroupMetadata,
- memberId: String,
- groupInstanceId: Option[String],
- clientId: String,
- clientHost: String,
- rebalanceTimeoutMs: Int,
- sessionTimeoutMs: Int,
- protocolType: String,
- protocols: List[(String, Array[Byte])],
- responseCallback: JoinCallback,
- reason: String
- ): Unit = {
- group.inLock {
- if (group.is(Dead)) {
- // if the group is marked as dead, it means some other thread has just removed the group
- // from the coordinator metadata; it is likely that the group has migrated to some other
- // coordinator OR the group is in a transient unstable phase. Let the member retry
- // finding the correct coordinator and rejoin.
- responseCallback(JoinGroupResult(memberId, Errors.COORDINATOR_NOT_AVAILABLE))
- } else if (!group.supportsProtocols(protocolType, MemberMetadata.plainProtocolSet(protocols))) {
- responseCallback(JoinGroupResult(memberId, Errors.INCONSISTENT_GROUP_PROTOCOL))
- } else if (group.isPendingMember(memberId)) {
- // A rejoining pending member will be accepted. Note that pending member cannot be a static member.
- groupInstanceId.foreach { instanceId =>
- throw new IllegalStateException(s"Received unexpected JoinGroup with groupInstanceId=$instanceId " +
- s"for pending member with memberId=$memberId")
- }
-
- info(s"Pending dynamic member with id $memberId joins group ${group.groupId} in " +
- s"${group.currentState} state. Adding to the group now.")
- addMemberAndRebalance(rebalanceTimeoutMs, sessionTimeoutMs, memberId, None,
- clientId, clientHost, protocolType, protocols, group, responseCallback, reason)
- } else {
- val memberErrorOpt = validateCurrentMember(
- group,
- memberId,
- groupInstanceId,
- operation = "join-group"
- )
-
- memberErrorOpt match {
- case Some(error) => responseCallback(JoinGroupResult(memberId, error))
-
- case None => group.currentState match {
- case PreparingRebalance =>
- val member = group.get(memberId)
- updateMemberAndRebalance(group, member, protocols, rebalanceTimeoutMs, sessionTimeoutMs, s"Member ${member.memberId} joining group during ${group.currentState}; client reason: $reason", responseCallback)
-
- case CompletingRebalance =>
- val member = group.get(memberId)
- if (member.matches(protocols)) {
- // member is joining with the same metadata (which could be because it failed to
- // receive the initial JoinGroup response), so just return current group information
- // for the current generation.
- responseCallback(JoinGroupResult(
- members = if (group.isLeader(memberId)) {
- group.currentMemberMetadata
- } else {
- List.empty
- },
- memberId = memberId,
- generationId = group.generationId,
- protocolType = group.protocolType,
- protocolName = group.protocolName,
- leaderId = group.leaderOrNull,
- skipAssignment = false,
- error = Errors.NONE))
- } else {
- // member has changed metadata, so force a rebalance
- updateMemberAndRebalance(group, member, protocols, rebalanceTimeoutMs, sessionTimeoutMs, s"Updating metadata for member ${member.memberId} during ${group.currentState}; client reason: $reason", responseCallback)
- }
-
- case Stable =>
- val member = group.get(memberId)
- if (group.isLeader(memberId)) {
- // force a rebalance if the leader sends JoinGroup;
- // This allows the leader to trigger rebalances for changes affecting assignment
- // which do not affect the member metadata (such as topic metadata changes for the consumer)
- updateMemberAndRebalance(group, member, protocols, rebalanceTimeoutMs, sessionTimeoutMs, s"Leader ${member.memberId} re-joining group during ${group.currentState}; client reason: $reason", responseCallback)
- } else if (!member.matches(protocols)) {
- updateMemberAndRebalance(group, member, protocols, rebalanceTimeoutMs, sessionTimeoutMs, s"Updating metadata for member ${member.memberId} during ${group.currentState}; client reason: $reason", responseCallback)
- } else {
- // for followers with no actual change to their metadata, just return group information
- // for the current generation which will allow them to issue SyncGroup
- responseCallback(JoinGroupResult(
- members = List.empty,
- memberId = memberId,
- generationId = group.generationId,
- protocolType = group.protocolType,
- protocolName = group.protocolName,
- leaderId = group.leaderOrNull,
- skipAssignment = false,
- error = Errors.NONE))
- }
-
- case Empty | Dead =>
- // Group reaches unexpected state. Let the joining member reset their generation and rejoin.
- warn(s"Attempt to add rejoining member $memberId of group ${group.groupId} in " +
- s"unexpected group state ${group.currentState}")
- responseCallback(JoinGroupResult(memberId, Errors.UNKNOWN_MEMBER_ID))
- }
- }
- }
- }
- }
-
- def handleSyncGroup(groupId: String,
- generation: Int,
- memberId: String,
- protocolType: Option[String],
- protocolName: Option[String],
- groupInstanceId: Option[String],
- groupAssignment: Map[String, Array[Byte]],
- responseCallback: SyncCallback,
- requestLocal: RequestLocal = RequestLocal.noCaching): Unit = {
- validateGroupStatus(groupId, ApiKeys.SYNC_GROUP) match {
- case Some(error) if error == Errors.COORDINATOR_LOAD_IN_PROGRESS =>
- // The coordinator is loading, which means we've lost the state of the active rebalance and the
- // group will need to start over at JoinGroup. By returning rebalance in progress, the consumer
- // will attempt to rejoin without needing to rediscover the coordinator. Note that we cannot
- // return COORDINATOR_LOAD_IN_PROGRESS since older clients do not expect the error.
- responseCallback(SyncGroupResult(Errors.REBALANCE_IN_PROGRESS))
-
- case Some(error) => responseCallback(SyncGroupResult(error))
-
- case None =>
- groupManager.getGroup(groupId) match {
- case None => responseCallback(SyncGroupResult(Errors.UNKNOWN_MEMBER_ID))
- case Some(group) => doSyncGroup(group, generation, memberId, protocolType, protocolName,
- groupInstanceId, groupAssignment, requestLocal, responseCallback)
- }
- }
- }
-
- private def validateSyncGroup(
- group: GroupMetadata,
- generationId: Int,
- memberId: String,
- protocolType: Option[String],
- protocolName: Option[String],
- groupInstanceId: Option[String],
- ): Option[Errors] = {
- if (group.is(Dead)) {
- // if the group is marked as dead, it means some other thread has just removed the group
- // from the coordinator metadata; this is likely that the group has migrated to some other
- // coordinator OR the group is in a transient unstable phase. Let the member retry
- // finding the correct coordinator and rejoin.
- Some(Errors.COORDINATOR_NOT_AVAILABLE)
- } else {
- validateCurrentMember(
- group,
- memberId,
- groupInstanceId,
- operation = "sync-group"
- ).orElse {
- if (generationId != group.generationId) {
- Some(Errors.ILLEGAL_GENERATION)
- } else if (protocolType.isDefined && !group.protocolType.contains(protocolType.get)) {
- Some(Errors.INCONSISTENT_GROUP_PROTOCOL)
- } else if (protocolName.isDefined && !group.protocolName.contains(protocolName.get)) {
- Some(Errors.INCONSISTENT_GROUP_PROTOCOL)
- } else {
- None
- }
- }
- }
- }
-
- private def doSyncGroup(group: GroupMetadata,
- generationId: Int,
- memberId: String,
- protocolType: Option[String],
- protocolName: Option[String],
- groupInstanceId: Option[String],
- groupAssignment: Map[String, Array[Byte]],
- requestLocal: RequestLocal,
- responseCallback: SyncCallback): Unit = {
- group.inLock {
- val validationErrorOpt = validateSyncGroup(
- group,
- generationId,
- memberId,
- protocolType,
- protocolName,
- groupInstanceId
- )
-
- validationErrorOpt match {
- case Some(error) => responseCallback(SyncGroupResult(error))
-
- case None => group.currentState match {
- case Empty =>
- responseCallback(SyncGroupResult(Errors.UNKNOWN_MEMBER_ID))
-
- case PreparingRebalance =>
- responseCallback(SyncGroupResult(Errors.REBALANCE_IN_PROGRESS))
-
- case CompletingRebalance =>
- group.get(memberId).awaitingSyncCallback = responseCallback
- removePendingSyncMember(group, memberId)
-
- // if this is the leader, then we can attempt to persist state and transition to stable
- if (group.isLeader(memberId)) {
- info(s"Assignment received from leader $memberId for group ${group.groupId} for generation ${group.generationId}. " +
- s"The group has ${group.size} members, ${group.allStaticMembers.size} of which are static.")
-
- // fill any missing members with an empty assignment
- val missing = group.allMembers.diff(groupAssignment.keySet)
- val assignment = groupAssignment ++ missing.map(_ -> Array.empty[Byte]).toMap
-
- if (missing.nonEmpty) {
- warn(s"Setting empty assignments for members $missing of ${group.groupId} for generation ${group.generationId}")
- }
-
- groupManager.storeGroup(group, assignment, (error: Errors) => {
- group.inLock {
- // another member may have joined the group while we were awaiting this callback,
- // so we must ensure we are still in the CompletingRebalance state and the same generation
- // when it gets invoked. if we have transitioned to another state, then do nothing
- if (group.is(CompletingRebalance) && generationId == group.generationId) {
- if (error != Errors.NONE) {
- resetAndPropagateAssignmentError(group, error)
- maybePrepareRebalance(group, s"Error $error when storing group assignment during SyncGroup (member: $memberId)")
- } else {
- setAndPropagateAssignment(group, assignment)
- group.transitionTo(Stable)
- }
- }
- }
- }, requestLocal)
- groupCompletedRebalanceSensor.record()
- }
-
- case Stable =>
- removePendingSyncMember(group, memberId)
-
- // if the group is stable, we just return the current assignment
- val memberMetadata = group.get(memberId)
- responseCallback(SyncGroupResult(group.protocolType, group.protocolName, memberMetadata.assignment, Errors.NONE))
- completeAndScheduleNextHeartbeatExpiration(group, group.get(memberId))
-
- case Dead =>
- throw new IllegalStateException(s"Reached unexpected condition for Dead group ${group.groupId}")
- }
- }
- }
- }
-
- def handleLeaveGroup(groupId: String,
- leavingMembers: List[MemberIdentity],
- responseCallback: LeaveGroupResult => Unit): Unit = {
-
- def removeCurrentMemberFromGroup(group: GroupMetadata, memberId: String, reason: Option[String]): Unit = {
- val member = group.get(memberId)
- val leaveReason = reason.getOrElse("not provided")
- removeMemberAndUpdateGroup(group, member, s"Removing member $memberId on LeaveGroup; client reason: $leaveReason")
- removeHeartbeatForLeavingMember(group, member.memberId)
- info(s"Member $member has left group $groupId through explicit `LeaveGroup`; client reason: $leaveReason")
- }
-
- validateGroupStatus(groupId, ApiKeys.LEAVE_GROUP) match {
- case Some(error) =>
- responseCallback(leaveError(error, List.empty))
- case None =>
- groupManager.getGroup(groupId) match {
- case None =>
- responseCallback(leaveError(Errors.NONE, leavingMembers.map {leavingMember =>
- memberLeaveError(leavingMember, Errors.UNKNOWN_MEMBER_ID)
- }))
- case Some(group) =>
- group.inLock {
- if (group.is(Dead)) {
- responseCallback(leaveError(Errors.COORDINATOR_NOT_AVAILABLE, List.empty))
- } else {
- val memberErrors = leavingMembers.map { leavingMember =>
- val memberId = leavingMember.memberId
- val groupInstanceId = Option(leavingMember.groupInstanceId)
- val reason = Option(leavingMember.reason)
-
- // The LeaveGroup API allows administrative removal of members by GroupInstanceId
- // in which case we expect the MemberId to be undefined.
- if (memberId == JoinGroupRequest.UNKNOWN_MEMBER_ID) {
- groupInstanceId.flatMap(group.currentStaticMemberId) match {
- case Some(currentMemberId) =>
- removeCurrentMemberFromGroup(group, currentMemberId, reason)
- memberLeaveError(leavingMember, Errors.NONE)
- case None =>
- memberLeaveError(leavingMember, Errors.UNKNOWN_MEMBER_ID)
- }
- } else if (group.isPendingMember(memberId)) {
- removePendingMemberAndUpdateGroup(group, memberId)
- heartbeatPurgatory.checkAndComplete(new MemberKey(group.groupId, memberId))
- info(s"Pending member with memberId=$memberId has left group ${group.groupId} " +
- s"through explicit `LeaveGroup` request")
- memberLeaveError(leavingMember, Errors.NONE)
- } else {
- val memberError = validateCurrentMember(
- group,
- memberId,
- groupInstanceId,
- operation = "leave-group"
- ).getOrElse {
- removeCurrentMemberFromGroup(group, memberId, reason)
- Errors.NONE
- }
- memberLeaveError(leavingMember, memberError)
- }
- }
- responseCallback(leaveError(Errors.NONE, memberErrors))
- }
- }
- }
- }
- }
-
- def handleDeleteGroups(groupIds: Set[String],
- requestLocal: RequestLocal = RequestLocal.noCaching): Map[String, Errors] = {
- val groupErrors = mutable.Map.empty[String, Errors]
- val groupsEligibleForDeletion = mutable.ArrayBuffer[GroupMetadata]()
-
- groupIds.foreach { groupId =>
- validateGroupStatus(groupId, ApiKeys.DELETE_GROUPS) match {
- case Some(error) =>
- groupErrors += groupId -> error
-
- case None =>
- groupManager.getGroup(groupId) match {
- case None =>
- groupErrors += groupId ->
- (if (groupManager.groupNotExists(groupId)) Errors.GROUP_ID_NOT_FOUND else Errors.NOT_COORDINATOR)
- case Some(group) =>
- group.inLock {
- group.currentState match {
- case Dead =>
- groupErrors += groupId ->
- (if (groupManager.groupNotExists(groupId)) Errors.GROUP_ID_NOT_FOUND else Errors.NOT_COORDINATOR)
- case Empty =>
- group.transitionTo(Dead)
- groupsEligibleForDeletion += group
- case Stable | PreparingRebalance | CompletingRebalance =>
- groupErrors(groupId) = Errors.NON_EMPTY_GROUP
- }
- }
- }
- }
- }
-
- if (groupsEligibleForDeletion.nonEmpty) {
- val offsetsRemoved = groupManager.cleanupGroupMetadata(groupsEligibleForDeletion, requestLocal,
- _.removeAllOffsets())
- groupErrors ++= groupsEligibleForDeletion.map(_.groupId -> Errors.NONE).toMap
- info(s"The following groups were deleted: ${groupsEligibleForDeletion.map(_.groupId).mkString(", ")}. " +
- s"A total of $offsetsRemoved offsets were removed.")
- }
-
- groupErrors
- }
-
- def handleDeleteOffsets(groupId: String, partitions: Seq[TopicPartition],
- requestLocal: RequestLocal): (Errors, Map[TopicPartition, Errors]) = {
- var groupError: Errors = Errors.NONE
- var partitionErrors: Map[TopicPartition, Errors] = Map()
- var partitionsEligibleForDeletion: Seq[TopicPartition] = Seq()
-
- validateGroupStatus(groupId, ApiKeys.OFFSET_DELETE) match {
- case Some(error) =>
- groupError = error
-
- case None =>
- groupManager.getGroup(groupId) match {
- case None =>
- groupError = if (groupManager.groupNotExists(groupId))
- Errors.GROUP_ID_NOT_FOUND else Errors.NOT_COORDINATOR
-
- case Some(group) =>
- group.inLock {
- group.currentState match {
- case Dead =>
- groupError = if (groupManager.groupNotExists(groupId))
- Errors.GROUP_ID_NOT_FOUND else Errors.NOT_COORDINATOR
-
- case Empty =>
- partitionsEligibleForDeletion = partitions
-
- case PreparingRebalance | CompletingRebalance | Stable if group.isConsumerGroup =>
- val (consumed, notConsumed) =
- partitions.partition(tp => group.isSubscribedToTopic(tp.topic()))
-
- partitionsEligibleForDeletion = notConsumed
- partitionErrors = consumed.map(_ -> Errors.GROUP_SUBSCRIBED_TO_TOPIC).toMap
-
- case _ =>
- groupError = Errors.NON_EMPTY_GROUP
- }
- }
-
- if (partitionsEligibleForDeletion.nonEmpty) {
- val offsetsRemoved = groupManager.cleanupGroupMetadata(Seq(group), requestLocal,
- _.removeOffsets(partitionsEligibleForDeletion))
-
- partitionErrors ++= partitionsEligibleForDeletion.map(_ -> Errors.NONE).toMap
-
- offsetDeletionSensor.record(offsetsRemoved)
-
- info(s"The following offsets of the group $groupId were deleted: ${partitionsEligibleForDeletion.mkString(", ")}. " +
- s"A total of $offsetsRemoved offsets were removed.")
- }
- }
- }
-
- // If there is a group error, the partition errors is empty
- groupError -> partitionErrors
- }
-
- private def validateHeartbeat(
- group: GroupMetadata,
- generationId: Int,
- memberId: String,
- groupInstanceId: Option[String]
- ): Option[Errors] = {
- if (group.is(Dead)) {
- Some(Errors.COORDINATOR_NOT_AVAILABLE)
- } else {
- validateCurrentMember(
- group,
- memberId,
- groupInstanceId,
- operation = "heartbeat"
- ).orElse {
- if (generationId != group.generationId) {
- Some(Errors.ILLEGAL_GENERATION)
- } else {
- None
- }
- }
- }
- }
-
- def handleHeartbeat(groupId: String,
- memberId: String,
- groupInstanceId: Option[String],
- generationId: Int,
- responseCallback: Errors => Unit): Unit = {
- validateGroupStatus(groupId, ApiKeys.HEARTBEAT).foreach { error =>
- if (error == Errors.COORDINATOR_LOAD_IN_PROGRESS)
- // the group is still loading, so respond just blindly
- responseCallback(Errors.NONE)
- else
- responseCallback(error)
- return
- }
-
- val err = groupManager.getGroup(groupId) match {
- case None =>
- Errors.UNKNOWN_MEMBER_ID
-
- case Some(group) => group.inLock {
- val validationErrorOpt = validateHeartbeat(
- group,
- generationId,
- memberId,
- groupInstanceId
- )
-
- if (validationErrorOpt.isDefined) {
- validationErrorOpt.get
- } else {
- group.currentState match {
- case Empty =>
- Errors.UNKNOWN_MEMBER_ID
-
- case CompletingRebalance =>
- // consumers may start sending heartbeat after join-group response, in which case
- // we should treat them as normal hb request and reset the timer
- val member = group.get(memberId)
- completeAndScheduleNextHeartbeatExpiration(group, member)
- Errors.NONE
-
- case PreparingRebalance =>
- val member = group.get(memberId)
- completeAndScheduleNextHeartbeatExpiration(group, member)
- Errors.REBALANCE_IN_PROGRESS
-
- case Stable =>
- val member = group.get(memberId)
- completeAndScheduleNextHeartbeatExpiration(group, member)
- Errors.NONE
-
- case Dead =>
- throw new IllegalStateException(s"Reached unexpected condition for Dead group $groupId")
- }
- }
- }
- }
- responseCallback(err)
- }
-
- def handleTxnCommitOffsets(groupId: String,
- transactionalId: String,
- producerId: Long,
- producerEpoch: Short,
- memberId: String,
- groupInstanceId: Option[String],
- generationId: Int,
- offsetMetadata: immutable.Map[TopicIdPartition, OffsetAndMetadata],
- responseCallback: immutable.Map[TopicIdPartition, Errors] => Unit,
- requestLocal: RequestLocal = RequestLocal.noCaching,
- apiVersion: Short): Unit = {
- validateGroupStatus(groupId, ApiKeys.TXN_OFFSET_COMMIT) match {
- case Some(error) => responseCallback(offsetMetadata.map { case (k, _) => k -> error })
- case None =>
- val group = groupManager.getGroup(groupId).getOrElse {
- groupManager.addGroup(new GroupMetadata(groupId, Empty, time))
- }
-
- val offsetTopicPartition = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, partitionFor(group.groupId))
-
- def postVerificationCallback(
- newRequestLocal: RequestLocal,
- errorAndGuard: (Errors, VerificationGuard)
- ): Unit = {
- val (error, verificationGuard) = errorAndGuard
- if (error != Errors.NONE) {
- val finalError = GroupMetadataManager.maybeConvertOffsetCommitError(error)
- responseCallback(offsetMetadata.map { case (k, _) => k -> finalError })
- } else {
- doTxnCommitOffsets(group, memberId, groupInstanceId, generationId, producerId, producerEpoch,
- offsetTopicPartition, offsetMetadata, newRequestLocal, responseCallback, Some(verificationGuard))
- }
- }
- val transactionSupportedOperation = AddPartitionsToTxnManager.txnOffsetCommitRequestVersionToTransactionSupportedOperation(apiVersion)
- groupManager.replicaManager.maybeSendPartitionToTransactionCoordinator(
- topicPartition = offsetTopicPartition,
- transactionalId,
- producerId,
- producerEpoch,
- RecordBatch.NO_SEQUENCE,
- // Wrap the callback to be handled on an arbitrary request handler thread
- // when transaction verification is complete. The request local passed in
- // is only used when the callback is executed immediately.
- KafkaRequestHandler.wrapAsyncCallback(
- postVerificationCallback,
- requestLocal
- ),
- transactionSupportedOperation
- )
- }
- }
-
- def handleCommitOffsets(groupId: String,
- memberId: String,
- groupInstanceId: Option[String],
- generationId: Int,
- offsetMetadata: immutable.Map[TopicIdPartition, OffsetAndMetadata],
- responseCallback: immutable.Map[TopicIdPartition, Errors] => Unit,
- requestLocal: RequestLocal = RequestLocal.noCaching): Unit = {
- validateGroupStatus(groupId, ApiKeys.OFFSET_COMMIT) match {
- case Some(error) => responseCallback(offsetMetadata.map { case (k, _) => k -> error })
- case None =>
- groupManager.getGroup(groupId) match {
- case None =>
- if (generationId < 0) {
- // the group is not relying on Kafka for group management, so allow the commit
- info(s"Creating simple consumer group $groupId via manual offset commit.")
- val group = groupManager.addGroup(new GroupMetadata(groupId, Empty, time))
- doCommitOffsets(group, memberId, groupInstanceId, generationId, offsetMetadata,
- responseCallback, requestLocal)
- } else {
- // or this is a request coming from an older generation. either way, reject the commit
- responseCallback(offsetMetadata.map { case (k, _) => k -> Errors.ILLEGAL_GENERATION })
- }
-
- case Some(group) =>
- doCommitOffsets(group, memberId, groupInstanceId, generationId, offsetMetadata,
- responseCallback, requestLocal)
- }
- }
- }
-
- def scheduleHandleTxnCompletion(producerId: Long,
- offsetsPartitions: Iterable[TopicPartition],
- transactionResult: TransactionResult): CompletableFuture[Void] = {
- require(offsetsPartitions.forall(_.topic == Topic.GROUP_METADATA_TOPIC_NAME))
- val isCommit = transactionResult == TransactionResult.COMMIT
- groupManager.scheduleHandleTxnCompletion(producerId, offsetsPartitions.map(_.partition).toSet, isCommit)
- }
-
- private def doTxnCommitOffsets(group: GroupMetadata,
- memberId: String,
- groupInstanceId: Option[String],
- generationId: Int,
- producerId: Long,
- producerEpoch: Short,
- offsetTopicPartition: TopicPartition,
- offsetMetadata: immutable.Map[TopicIdPartition, OffsetAndMetadata],
- requestLocal: RequestLocal,
- responseCallback: immutable.Map[TopicIdPartition, Errors] => Unit,
- verificationGuard: Option[VerificationGuard]): Unit = {
- group.inLock {
- val validationErrorOpt = validateOffsetCommit(
- group,
- generationId,
- memberId,
- groupInstanceId,
- isTransactional = true
- )
-
- if (validationErrorOpt.isDefined) {
- responseCallback(offsetMetadata.map { case (k, _) => k -> validationErrorOpt.get })
- } else {
- groupManager.storeOffsets(group, memberId, offsetTopicPartition, offsetMetadata, responseCallback, producerId,
- producerEpoch, requestLocal, verificationGuard)
- }
- }
- }
-
- private def validateOffsetCommit(
- group: GroupMetadata,
- generationId: Int,
- memberId: String,
- groupInstanceId: Option[String],
- isTransactional: Boolean
- ): Option[Errors] = {
- if (group.is(Dead)) {
- Some(Errors.COORDINATOR_NOT_AVAILABLE)
- } else if (generationId < 0 && group.is(Empty)) {
- // When the generation id is -1, the request comes from either the admin client
- // or a consumer which does not use the group management facility. In this case,
- // the request can commit offsets if the group is empty.
- None
- } else if (generationId >= 0 || memberId != JoinGroupRequest.UNKNOWN_MEMBER_ID || groupInstanceId.isDefined) {
- validateCurrentMember(
- group,
- memberId,
- groupInstanceId,
- operation = if (isTransactional) "txn-offset-commit" else "offset-commit"
- ).orElse {
- if (generationId != group.generationId) {
- Some(Errors.ILLEGAL_GENERATION)
- } else {
- None
- }
- }
- } else if (!isTransactional && !group.is(Empty)) {
- // When the group is non-empty, only members can commit offsets.
- // This does not apply to transactional offset commits, since the
- // older versions of this protocol do not require memberId and
- // generationId.
- Some(Errors.UNKNOWN_MEMBER_ID)
- } else {
- None
- }
- }
-
- private def doCommitOffsets(group: GroupMetadata,
- memberId: String,
- groupInstanceId: Option[String],
- generationId: Int,
- offsetMetadata: immutable.Map[TopicIdPartition, OffsetAndMetadata],
- responseCallback: immutable.Map[TopicIdPartition, Errors] => Unit,
- requestLocal: RequestLocal): Unit = {
- group.inLock {
- val validationErrorOpt = validateOffsetCommit(
- group,
- generationId,
- memberId,
- groupInstanceId,
- isTransactional = false
- )
-
- val offsetTopicPartition = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, partitionFor(group.groupId))
-
- if (validationErrorOpt.isDefined) {
- responseCallback(offsetMetadata.map { case (k, _) => k -> validationErrorOpt.get })
- } else {
- group.currentState match {
- case Empty =>
- groupManager.storeOffsets(group, memberId, offsetTopicPartition, offsetMetadata, responseCallback, verificationGuard = None)
-
- case Stable | PreparingRebalance =>
- // During PreparingRebalance phase, we still allow a commit request since we rely
- // on heartbeat response to eventually notify the rebalance in progress signal to the consumer
- val member = group.get(memberId)
- completeAndScheduleNextHeartbeatExpiration(group, member)
- groupManager.storeOffsets(group, memberId, offsetTopicPartition, offsetMetadata, responseCallback, requestLocal = requestLocal, verificationGuard = None)
-
- case CompletingRebalance =>
- // We should not receive a commit request if the group has not completed rebalance;
- // but since the consumer's member.id and generation is valid, it means it has received
- // the latest group generation information from the JoinResponse.
- // So let's return a REBALANCE_IN_PROGRESS to let consumer handle it gracefully.
- responseCallback(offsetMetadata.map { case (k, _) => k -> Errors.REBALANCE_IN_PROGRESS })
-
- case _ =>
- throw new RuntimeException(s"Logic error: unexpected group state ${group.currentState}")
- }
- }
- }
- }
-
- def handleFetchOffsets(
- groupId: String,
- requireStable: Boolean,
- partitions: Option[Seq[TopicPartition]] = None
- ): (Errors, Map[TopicPartition, OffsetFetchResponse.PartitionData]) = {
-
- validateGroupStatus(groupId, ApiKeys.OFFSET_FETCH) match {
- case Some(error) => error -> Map.empty
- case None =>
- // return offsets blindly regardless the current group state since the group may be using
- // Kafka commit storage without automatic group management
- (Errors.NONE, groupManager.getOffsets(groupId, requireStable, partitions))
- }
- }
-
- def handleListGroups(states: Set[String], groupTypes: Set[String]): (Errors, List[GroupOverview]) = {
- if (!isActive.get) {
- (Errors.COORDINATOR_NOT_AVAILABLE, List[GroupOverview]())
- } else {
- val errorCode = if (groupManager.isLoading) Errors.COORDINATOR_LOAD_IN_PROGRESS else Errors.NONE
-
- // Convert state filter strings to lower case and group type strings to the corresponding enum type.
- // This is done to ensure a case-insensitive comparison.
- val caseInsensitiveStates = states.map(_.toLowerCase)
- val enumTypesFilter: Set[Group.GroupType] = groupTypes.map(Group.GroupType.parse)
-
- // Filter groups based on states and groupTypes. If either is empty, it won't filter on that criterion.
- // While using the old group coordinator, all groups are considered classic groups by default.
- // An empty list is returned for any other type filter.
- val groups = groupManager.currentGroups.filter { g =>
- (states.isEmpty || g.isInStates(caseInsensitiveStates)) &&
- (enumTypesFilter.isEmpty || enumTypesFilter.contains(Group.GroupType.CLASSIC))
- }
- (errorCode, groups.map(_.overview).toList)
- }
- }
-
- def handleDescribeGroup(groupId: String, apiVersion: Short): (Errors, Option[String], GroupSummary) = {
- validateGroupStatus(groupId, ApiKeys.DESCRIBE_GROUPS) match {
- case Some(error) => (error, None, GroupCoordinator.EmptyGroup)
- case None =>
- groupManager.getGroup(groupId) match {
- case None =>
- if (apiVersion >= 6) {
- (Errors.GROUP_ID_NOT_FOUND, Some(s"Group $groupId not found."), GroupCoordinator.DeadGroup)
- } else {
- (Errors.NONE, None, GroupCoordinator.DeadGroup)
- }
- case Some(group) =>
- group.inLock {
- (Errors.NONE, None, group.summary)
- }
- }
- }
- }
-
- def handleDeletedPartitions(topicPartitions: Seq[TopicPartition], requestLocal: RequestLocal): Unit = {
- val offsetsRemoved = groupManager.cleanupGroupMetadata(groupManager.currentGroups, requestLocal,
- _.removeOffsets(topicPartitions))
- info(s"Removed $offsetsRemoved offsets associated with deleted partitions: ${topicPartitions.mkString(", ")}.")
- }
-
- private def isValidGroupId(groupId: String, api: ApiKeys): Boolean = {
- api match {
- case ApiKeys.OFFSET_COMMIT | ApiKeys.OFFSET_FETCH | ApiKeys.DESCRIBE_GROUPS | ApiKeys.DELETE_GROUPS =>
- // For backwards compatibility, we support the offset commit APIs for the empty groupId, and also
- // in DescribeGroups and DeleteGroups so that users can view and delete state of all groups.
- groupId != null
- case _ =>
- // The remaining APIs are groups using Kafka for group coordination and must have a non-empty groupId
- groupId != null && groupId.nonEmpty
- }
- }
-
- /**
- * Check that the groupId is valid, assigned to this coordinator and that the group has been loaded.
- */
- private def validateGroupStatus(groupId: String, api: ApiKeys): Option[Errors] = {
- if (!isValidGroupId(groupId, api))
- Some(Errors.INVALID_GROUP_ID)
- else if (!isActive.get)
- Some(Errors.COORDINATOR_NOT_AVAILABLE)
- else if (isCoordinatorLoadInProgress(groupId))
- Some(Errors.COORDINATOR_LOAD_IN_PROGRESS)
- else if (!isCoordinatorForGroup(groupId))
- Some(Errors.NOT_COORDINATOR)
- else
- None
- }
-
- private def onGroupUnloaded(group: GroupMetadata): Unit = {
- group.inLock {
- info(s"Unloading group metadata for ${group.groupId} with generation ${group.generationId}")
- val previousState = group.currentState
- group.transitionTo(Dead)
-
- previousState match {
- case Empty | Dead =>
- case PreparingRebalance =>
- for (member <- group.allMemberMetadata) {
- group.maybeInvokeJoinCallback(member, JoinGroupResult(member.memberId, Errors.NOT_COORDINATOR))
- }
-
- rebalancePurgatory.checkAndComplete(new GroupJoinKey(group.groupId))
-
- case Stable | CompletingRebalance =>
- for (member <- group.allMemberMetadata) {
- group.maybeInvokeSyncCallback(member, SyncGroupResult(Errors.NOT_COORDINATOR))
- heartbeatPurgatory.checkAndComplete(new MemberKey(group.groupId, member.memberId))
- }
- }
-
- removeSyncExpiration(group)
- }
- }
-
- private def onGroupLoaded(group: GroupMetadata): Unit = {
- group.inLock {
- info(s"Loading group metadata for ${group.groupId} with generation ${group.generationId}")
- assert(group.is(Stable) || group.is(Empty))
- if (groupIsOverCapacity(group)) {
- prepareRebalance(group, s"Freshly-loaded group is over capacity (${groupConfig.groupMaxSize}). " +
- "Rebalancing in order to give a chance for consumers to commit offsets")
- }
-
- group.allMemberMetadata.foreach(completeAndScheduleNextHeartbeatExpiration(group, _))
- }
- }
-
- /**
- * Load cached state from the given partition and begin handling requests for groups which map to it.
- *
- * @param offsetTopicPartitionId The partition we are now leading
- */
- def onElection(offsetTopicPartitionId: Int, coordinatorEpoch: Int): Unit = {
- info(s"Elected as the group coordinator for partition $offsetTopicPartitionId in epoch $coordinatorEpoch")
- groupManager.scheduleLoadGroupAndOffsets(offsetTopicPartitionId, coordinatorEpoch, onGroupLoaded)
- }
-
- /**
- * Unload cached state for the given partition and stop handling requests for groups which map to it.
- *
- * @param offsetTopicPartitionId The partition we are no longer leading
- */
- def onResignation(offsetTopicPartitionId: Int, coordinatorEpoch: OptionalInt): Unit = {
- info(s"Resigned as the group coordinator for partition $offsetTopicPartitionId in epoch $coordinatorEpoch")
- groupManager.removeGroupsForPartition(offsetTopicPartitionId, coordinatorEpoch, onGroupUnloaded)
- }
-
- private def setAndPropagateAssignment(group: GroupMetadata, assignment: Map[String, Array[Byte]]): Unit = {
- assert(group.is(CompletingRebalance))
- group.allMemberMetadata.foreach(member => member.assignment = assignment(member.memberId))
- propagateAssignment(group, Errors.NONE)
- }
-
- private def resetAndPropagateAssignmentError(group: GroupMetadata, error: Errors): Unit = {
- assert(group.is(CompletingRebalance))
- group.allMemberMetadata.foreach(_.assignment = Array.empty)
- propagateAssignment(group, error)
- }
-
- private def propagateAssignment(group: GroupMetadata, error: Errors): Unit = {
- val (protocolType, protocolName) = if (error == Errors.NONE)
- (group.protocolType, group.protocolName)
- else
- (None, None)
- for (member <- group.allMemberMetadata) {
- if (member.assignment.isEmpty && error == Errors.NONE) {
- warn(s"Sending empty assignment to member ${member.memberId} of ${group.groupId} for generation ${group.generationId} with no errors")
- }
-
- if (group.maybeInvokeSyncCallback(member, SyncGroupResult(protocolType, protocolName, member.assignment, error))) {
- // reset the session timeout for members after propagating the member's assignment.
- // This is because if any member's session expired while we were still awaiting either
- // the leader sync group or the storage callback, its expiration will be ignored and no
- // future heartbeat expectations will not be scheduled.
- completeAndScheduleNextHeartbeatExpiration(group, member)
- }
- }
- }
-
- /**
- * Complete existing DelayedHeartbeats for the given member and schedule the next one
- */
- private def completeAndScheduleNextHeartbeatExpiration(group: GroupMetadata, member: MemberMetadata): Unit = {
- completeAndScheduleNextExpiration(group, member, member.sessionTimeoutMs)
- }
-
- private def completeAndScheduleNextExpiration(group: GroupMetadata, member: MemberMetadata, timeoutMs: Long): Unit = {
- val memberKey = new MemberKey(group.groupId, member.memberId)
-
- // complete current heartbeat expectation
- member.heartbeatSatisfied = true
- heartbeatPurgatory.checkAndComplete(memberKey)
-
- // reschedule the next heartbeat expiration deadline
- member.heartbeatSatisfied = false
- val delayedHeartbeat = new DelayedHeartbeat(this, group, member.memberId, isPending = false, timeoutMs)
- heartbeatPurgatory.tryCompleteElseWatch(delayedHeartbeat, util.Collections.singletonList(memberKey))
- }
-
- /**
- * Add pending member expiration to heartbeat purgatory
- */
- private def addPendingMemberExpiration(group: GroupMetadata, pendingMemberId: String, timeoutMs: Long): Unit = {
- val pendingMemberKey = new MemberKey(group.groupId, pendingMemberId)
- val delayedHeartbeat = new DelayedHeartbeat(this, group, pendingMemberId, isPending = true, timeoutMs)
- heartbeatPurgatory.tryCompleteElseWatch(delayedHeartbeat, util.Collections.singletonList(pendingMemberKey))
- }
-
- private def removeHeartbeatForLeavingMember(group: GroupMetadata, memberId: String): Unit = {
- val memberKey = new MemberKey(group.groupId, memberId)
- heartbeatPurgatory.checkAndComplete(memberKey)
- }
-
- private def addMemberAndRebalance(rebalanceTimeoutMs: Int,
- sessionTimeoutMs: Int,
- memberId: String,
- groupInstanceId: Option[String],
- clientId: String,
- clientHost: String,
- protocolType: String,
- protocols: List[(String, Array[Byte])],
- group: GroupMetadata,
- callback: JoinCallback,
- reason: String): Unit = {
- val member = new MemberMetadata(memberId, groupInstanceId, clientId, clientHost,
- rebalanceTimeoutMs, sessionTimeoutMs, protocolType, protocols)
-
- member.isNew = true
-
- // update the newMemberAdded flag to indicate that the join group can be further delayed
- if (group.is(PreparingRebalance) && group.generationId == 0)
- group.newMemberAdded = true
-
- group.add(member, callback)
-
- // The session timeout does not affect new members since they do not have their memberId and
- // cannot send heartbeats. Furthermore, we cannot detect disconnects because sockets are muted
- // while the JoinGroup is in purgatory. If the client does disconnect (e.g. because of a request
- // timeout during a long rebalance), they may simply retry which will lead to a lot of defunct
- // members in the rebalance. To prevent this going on indefinitely, we timeout JoinGroup requests
- // for new members. If the new member is still there, we expect it to retry.
- completeAndScheduleNextExpiration(group, member, NewMemberJoinTimeoutMs)
-
- maybePrepareRebalance(group, s"Adding new member $memberId with group instance id $groupInstanceId; client reason: $reason")
- }
-
- private def updateStaticMemberAndRebalance(
- group: GroupMetadata,
- oldMemberId: String,
- newMemberId: String,
- groupInstanceId: String,
- protocols: List[(String, Array[Byte])],
- rebalanceTimeoutMs: Int,
- sessionTimeoutMs: Int,
- responseCallback: JoinCallback,
- requestLocal: RequestLocal,
- reason: String,
- supportSkippingAssignment: Boolean
- ): Unit = {
- val currentLeader = group.leaderOrNull
- val member = group.replaceStaticMember(groupInstanceId, oldMemberId, newMemberId)
- // Heartbeat of old member id will expire without effect since the group no longer contains that member id.
- // New heartbeat shall be scheduled with new member id.
- completeAndScheduleNextHeartbeatExpiration(group, member)
-
- val knownStaticMember = group.get(newMemberId)
- val oldRebalanceTimeoutMs = knownStaticMember.rebalanceTimeoutMs
- val oldSessionTimeoutMs = knownStaticMember.sessionTimeoutMs
- group.updateMember(knownStaticMember, protocols, rebalanceTimeoutMs, sessionTimeoutMs, responseCallback)
- val oldProtocols = knownStaticMember.supportedProtocols
-
- group.currentState match {
- case Stable =>
- // check if group's selectedProtocol of next generation will change, if not, simply store group to persist the
- // updated static member, if yes, rebalance should be triggered to let the group's assignment and selectProtocol consistent
- val selectedProtocolOfNextGeneration = group.selectProtocol
- if (group.protocolName.contains(selectedProtocolOfNextGeneration)) {
- info(s"Static member which joins during Stable stage and doesn't affect selectProtocol will not trigger rebalance.")
- val groupAssignment: Map[String, Array[Byte]] = group.allMemberMetadata.map(member => member.memberId -> member.assignment).toMap
- groupManager.storeGroup(group, groupAssignment, error => {
- group.inLock {
- if (error != Errors.NONE) {
- warn(s"Failed to persist metadata for group ${group.groupId}: ${error.message}")
-
- // Failed to persist member.id of the given static member, revert the update of the static member in the group.
- group.updateMember(knownStaticMember, oldProtocols, oldRebalanceTimeoutMs, oldSessionTimeoutMs, null)
- val oldMember = group.replaceStaticMember(groupInstanceId, newMemberId, oldMemberId)
- completeAndScheduleNextHeartbeatExpiration(group, oldMember)
- responseCallback(JoinGroupResult(
- List.empty,
- memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID,
- generationId = group.generationId,
- protocolType = group.protocolType,
- protocolName = group.protocolName,
- leaderId = currentLeader,
- skipAssignment = false,
- error = error
- ))
- } else if (supportSkippingAssignment) {
- // Starting from version 9 of the JoinGroup API, static members are able to
- // skip running the assignor based on the `SkipAssignment` field. We leverage
- // this to tell the leader that it is the leader of the group but by skipping
- // running the assignor while the group is in stable state.
- // Notes:
- // 1) This allows the leader to continue monitoring metadata changes for the
- // group. Note that any metadata changes happening while the static leader is
- // down won't be noticed.
- // 2) The assignors are not idempotent nor free from side effects. This is why
- // we skip entirely the assignment step as it could generate a different group
- // assignment which would be ignored by the group coordinator because the group
- // is the stable state.
- val isLeader = group.isLeader(newMemberId)
- group.maybeInvokeJoinCallback(member, JoinGroupResult(
- members = if (isLeader) {
- group.currentMemberMetadata
- } else {
- List.empty
- },
- memberId = newMemberId,
- generationId = group.generationId,
- protocolType = group.protocolType,
- protocolName = group.protocolName,
- leaderId = group.leaderOrNull,
- skipAssignment = isLeader,
- error = Errors.NONE
- ))
- } else {
- // Prior to version 9 of the JoinGroup API, we wanted to avoid current leader
- // performing trivial assignment while the group is in stable stage, because
- // the new assignment in leader's next sync call won't be broadcast by a stable group.
- // This could be guaranteed by always returning the old leader id so that the current
- // leader won't assume itself as a leader based on the returned message, since the new
- // member.id won't match returned leader id, therefore no assignment will be performed.
- group.maybeInvokeJoinCallback(member, JoinGroupResult(
- members = List.empty,
- memberId = newMemberId,
- generationId = group.generationId,
- protocolType = group.protocolType,
- protocolName = group.protocolName,
- leaderId = currentLeader,
- skipAssignment = false,
- error = Errors.NONE
- ))
- }
- }
- }, requestLocal)
- } else {
- maybePrepareRebalance(group, s"Group's selectedProtocol will change because static member ${member.memberId} with instance id $groupInstanceId joined with change of protocol; client reason: $reason")
- }
- case CompletingRebalance =>
- // if the group is in after-sync stage, upon getting a new join-group of a known static member
- // we should still trigger a new rebalance, since the old member may already be sent to the leader
- // for assignment, and hence when the assignment gets back there would be a mismatch of the old member id
- // with the new replaced member id. As a result the new member id would not get any assignment.
- prepareRebalance(group, s"Updating metadata for static member ${member.memberId} with instance id $groupInstanceId; client reason: $reason")
- case Empty | Dead =>
- throw new IllegalStateException(s"Group ${group.groupId} was not supposed to be " +
- s"in the state ${group.currentState} when the unknown static member $groupInstanceId rejoins.")
- case PreparingRebalance =>
- }
- }
-
- private def updateMemberAndRebalance(group: GroupMetadata,
- member: MemberMetadata,
- protocols: List[(String, Array[Byte])],
- rebalanceTimeoutMs: Int,
- sessionTimeoutMs: Int,
- reason: String,
- callback: JoinCallback): Unit = {
- group.updateMember(member, protocols, rebalanceTimeoutMs, sessionTimeoutMs, callback)
- maybePrepareRebalance(group, reason)
- }
-
- private def maybePrepareRebalance(group: GroupMetadata, reason: String): Unit = {
- group.inLock {
- if (group.canRebalance)
- prepareRebalance(group, reason)
- }
- }
-
- // package private for testing
- private[group] def prepareRebalance(group: GroupMetadata, reason: String): Unit = {
- // if any members are awaiting sync, cancel their request and have them rejoin
- if (group.is(CompletingRebalance))
- resetAndPropagateAssignmentError(group, Errors.REBALANCE_IN_PROGRESS)
-
- // if a sync expiration is pending, cancel it.
- removeSyncExpiration(group)
-
- val delayedRebalance = if (group.is(Empty))
- new InitialDelayedJoin(this,
- rebalancePurgatory,
- group,
- groupConfig.groupInitialRebalanceDelayMs,
- groupConfig.groupInitialRebalanceDelayMs,
- max(group.rebalanceTimeoutMs - groupConfig.groupInitialRebalanceDelayMs, 0))
- else
- new DelayedJoin(this, group, group.rebalanceTimeoutMs)
-
- group.transitionTo(PreparingRebalance)
-
- info(s"Preparing to rebalance group ${group.groupId} in state ${group.currentState} with old generation " +
- s"${group.generationId} (${Topic.GROUP_METADATA_TOPIC_NAME}-${partitionFor(group.groupId)}) (reason: $reason)")
-
- val groupKey = new GroupJoinKey(group.groupId)
- rebalancePurgatory.tryCompleteElseWatch(delayedRebalance, util.Collections.singletonList(groupKey))
- }
-
- private def removeMemberAndUpdateGroup(group: GroupMetadata, member: MemberMetadata, reason: String): Unit = {
- // New members may timeout with a pending JoinGroup while the group is still rebalancing, so we have
- // to invoke the callback before removing the member. We return UNKNOWN_MEMBER_ID so that the consumer
- // will retry the JoinGroup request if is still active.
- group.maybeInvokeJoinCallback(member, JoinGroupResult(JoinGroupRequest.UNKNOWN_MEMBER_ID, Errors.UNKNOWN_MEMBER_ID))
- group.remove(member.memberId)
-
- group.currentState match {
- case Dead | Empty =>
- case Stable | CompletingRebalance => maybePrepareRebalance(group, reason)
- case PreparingRebalance => rebalancePurgatory.checkAndComplete(new GroupJoinKey(group.groupId))
- }
- }
-
- private def removePendingMemberAndUpdateGroup(group: GroupMetadata, memberId: String): Unit = {
- group.remove(memberId)
-
- if (group.is(PreparingRebalance)) {
- rebalancePurgatory.checkAndComplete(new GroupJoinKey(group.groupId))
- }
- }
-
- def tryCompleteJoin(group: GroupMetadata, forceComplete: () => Boolean): Boolean = {
- group.inLock {
- if (group.hasAllMembersJoined)
- forceComplete()
- else false
- }
- }
-
- def onCompleteJoin(group: GroupMetadata): Unit = {
- group.inLock {
- val notYetRejoinedDynamicMembers = group.notYetRejoinedMembers.filterNot(_._2.isStaticMember)
- if (notYetRejoinedDynamicMembers.nonEmpty) {
- info(s"Group ${group.groupId} removed dynamic members " +
- s"who haven't joined: ${notYetRejoinedDynamicMembers.keySet}")
-
- notYetRejoinedDynamicMembers.values.foreach { failedMember =>
- group.remove(failedMember.memberId)
- removeHeartbeatForLeavingMember(group, failedMember.memberId)
- }
- }
-
- if (group.is(Dead)) {
- info(s"Group ${group.groupId} is dead, skipping rebalance stage")
- } else if (!group.maybeElectNewJoinedLeader() && group.allMembers.nonEmpty) {
- // If all members are not rejoining, we will postpone the completion
- // of rebalance preparing stage, and send out another delayed operation
- // until session timeout removes all the non-responsive members.
- error(s"Group ${group.groupId} could not complete rebalance because no members rejoined")
- rebalancePurgatory.tryCompleteElseWatch(
- new DelayedJoin(this, group, group.rebalanceTimeoutMs),
- util.Collections.singletonList(new GroupJoinKey(group.groupId)))
- } else {
- group.initNextGeneration()
- if (group.is(Empty)) {
- info(s"Group ${group.groupId} with generation ${group.generationId} is now empty " +
- s"(${Topic.GROUP_METADATA_TOPIC_NAME}-${partitionFor(group.groupId)})")
-
- groupManager.storeGroup(group, Map.empty, error => {
- if (error != Errors.NONE) {
- // we failed to write the empty group metadata. If the broker fails before another rebalance,
- // the previous generation written to the log will become active again (and most likely timeout).
- // This should be safe since there are no active members in an empty generation, so we just warn.
- warn(s"Failed to write empty metadata for group ${group.groupId}: ${error.message}")
- }
- }, RequestLocal.noCaching)
- } else {
- info(s"Stabilized group ${group.groupId} generation ${group.generationId} " +
- s"(${Topic.GROUP_METADATA_TOPIC_NAME}-${partitionFor(group.groupId)}) with ${group.size} members")
-
- // trigger the awaiting join group response callback for all the members after rebalancing
- for (member <- group.allMemberMetadata) {
- val joinResult = JoinGroupResult(
- members = if (group.isLeader(member.memberId)) {
- group.currentMemberMetadata
- } else {
- List.empty
- },
- memberId = member.memberId,
- generationId = group.generationId,
- protocolType = group.protocolType,
- protocolName = group.protocolName,
- leaderId = group.leaderOrNull,
- skipAssignment = false,
- error = Errors.NONE)
-
- group.maybeInvokeJoinCallback(member, joinResult)
- completeAndScheduleNextHeartbeatExpiration(group, member)
- member.isNew = false
-
- group.addPendingSyncMember(member.memberId)
- }
-
- schedulePendingSync(group)
- }
- }
- }
- }
-
- private def removePendingSyncMember(
- group: GroupMetadata,
- memberId: String
- ): Unit = {
- group.removePendingSyncMember(memberId)
- maybeCompleteSyncExpiration(group)
- }
-
- private def removeSyncExpiration(
- group: GroupMetadata
- ): Unit = {
- group.clearPendingSyncMembers()
- maybeCompleteSyncExpiration(group)
- }
-
- private def maybeCompleteSyncExpiration(
- group: GroupMetadata
- ): Unit = {
- val groupKey = new GroupSyncKey(group.groupId)
- rebalancePurgatory.checkAndComplete(groupKey)
- }
-
- private def schedulePendingSync(
- group: GroupMetadata
- ): Unit = {
- val delayedSync = new DelayedSync(this, group, group.generationId, group.rebalanceTimeoutMs)
- val groupKey = new GroupSyncKey(group.groupId)
- rebalancePurgatory.tryCompleteElseWatch(delayedSync, util.Collections.singletonList(groupKey))
- }
-
- def tryCompletePendingSync(
- group: GroupMetadata,
- generationId: Int,
- forceComplete: () => Boolean
- ): Boolean = {
- group.inLock {
- if (generationId != group.generationId) {
- forceComplete()
- } else {
- group.currentState match {
- case Dead | Empty | PreparingRebalance =>
- forceComplete()
- case CompletingRebalance | Stable =>
- if (group.hasReceivedSyncFromAllMembers)
- forceComplete()
- else false
- }
- }
- }
- }
-
- def onExpirePendingSync(
- group: GroupMetadata,
- generationId: Int
- ): Unit = {
- group.inLock {
- if (generationId != group.generationId) {
- error(s"Received unexpected notification of sync expiration for ${group.groupId} " +
- s"with an old generation $generationId while the group has ${group.generationId}.")
- } else {
- group.currentState match {
- case Dead | Empty | PreparingRebalance =>
- error(s"Received unexpected notification of sync expiration after group ${group.groupId} " +
- s"already transitioned to the ${group.currentState} state.")
-
- case CompletingRebalance | Stable =>
- if (!group.hasReceivedSyncFromAllMembers) {
- val pendingSyncMembers = group.allPendingSyncMembers
-
- pendingSyncMembers.foreach { memberId =>
- group.remove(memberId)
- removeHeartbeatForLeavingMember(group, memberId)
- }
-
- debug(s"Group ${group.groupId} removed members who haven't " +
- s"sent their sync request: $pendingSyncMembers")
-
- prepareRebalance(group, s"Removing $pendingSyncMembers on pending sync request expiration")
- }
- }
- }
- }
- }
-
- def tryCompleteHeartbeat(group: GroupMetadata,
- memberId: String,
- isPending: Boolean,
- forceComplete: () => Boolean): Boolean = {
- group.inLock {
- // The group has been unloaded and invalid, we should complete the heartbeat.
- if (group.is(Dead)) {
- forceComplete()
- } else if (isPending) {
- // complete the heartbeat if the member has joined the group
- if (group.has(memberId)) {
- forceComplete()
- } else false
- } else if (shouldCompleteNonPendingHeartbeat(group, memberId)) {
- forceComplete()
- } else false
- }
- }
-
- def shouldCompleteNonPendingHeartbeat(group: GroupMetadata, memberId: String): Boolean = {
- if (group.has(memberId)) {
- val member = group.get(memberId)
- member.hasSatisfiedHeartbeat
- } else {
- debug(s"Member id $memberId was not found in ${group.groupId} during heartbeat completion check")
- true
- }
- }
-
- def onExpireHeartbeat(group: GroupMetadata, memberId: String, isPending: Boolean): Unit = {
- group.inLock {
- if (group.is(Dead)) {
- info(s"Received notification of heartbeat expiration for member $memberId after group ${group.groupId} had already been unloaded or deleted.")
- } else if (isPending) {
- info(s"Pending member $memberId in group ${group.groupId} has been removed after session timeout expiration.")
- removePendingMemberAndUpdateGroup(group, memberId)
- } else if (!group.has(memberId)) {
- debug(s"Member $memberId has already been removed from the group.")
- } else {
- val member = group.get(memberId)
- if (!member.hasSatisfiedHeartbeat) {
- info(s"Member ${member.memberId} in group ${group.groupId} has failed, removing it from the group")
- removeMemberAndUpdateGroup(group, member, s"removing member ${member.memberId} on heartbeat expiration")
- }
- }
- }
- }
-
- def partitionFor(group: String): Int = groupManager.partitionFor(group)
-
- private def groupIsOverCapacity(group: GroupMetadata): Boolean = {
- group.size > groupConfig.groupMaxSize
- }
-
- private def isCoordinatorForGroup(groupId: String) = groupManager.isGroupLocal(groupId)
-
- private def isCoordinatorLoadInProgress(groupId: String) = groupManager.isGroupLoading(groupId)
-}
-
-object GroupCoordinator {
-
- val NoState = ""
- val NoProtocolType = ""
- val NoProtocol = ""
- val NoLeader = ""
- val NoGeneration = -1
- val NoMembers = List[MemberSummary]()
- val EmptyGroup = GroupSummary(NoState, NoProtocolType, NoProtocol, NoMembers)
- val DeadGroup = GroupSummary(Dead.toString, NoProtocolType, NoProtocol, NoMembers)
- val NewMemberJoinTimeoutMs: Int = 5 * 60 * 1000
-
- private[group] def apply(
- config: KafkaConfig,
- replicaManager: ReplicaManager,
- time: Time,
- metrics: Metrics
- ): GroupCoordinator = {
- val heartbeatPurgatory = new DelayedOperationPurgatory[DelayedHeartbeat]("Heartbeat", config.brokerId)
- val rebalancePurgatory = new DelayedOperationPurgatory[DelayedRebalance]("Rebalance", config.brokerId)
- GroupCoordinator(config, replicaManager, heartbeatPurgatory, rebalancePurgatory, time, metrics)
- }
-
- private[group] def offsetConfig(config: KafkaConfig) = new OffsetConfig(
- config.groupCoordinatorConfig.offsetMetadataMaxSize,
- config.groupCoordinatorConfig.offsetsLoadBufferSize,
- config.groupCoordinatorConfig.offsetsRetentionMs,
- config.groupCoordinatorConfig.offsetsRetentionCheckIntervalMs,
- config.groupCoordinatorConfig.offsetsTopicPartitions,
- config.groupCoordinatorConfig.offsetsTopicSegmentBytes,
- config.groupCoordinatorConfig.offsetsTopicReplicationFactor,
- config.groupCoordinatorConfig.offsetTopicCompressionType,
- config.groupCoordinatorConfig.offsetCommitTimeoutMs
- )
-
- private[group] def apply(
- config: KafkaConfig,
- replicaManager: ReplicaManager,
- heartbeatPurgatory: DelayedOperationPurgatory[DelayedHeartbeat],
- rebalancePurgatory: DelayedOperationPurgatory[DelayedRebalance],
- time: Time,
- metrics: Metrics
- ): GroupCoordinator = {
- val offsetConfig = this.offsetConfig(config)
- val groupConfig = GroupConfig(groupMinSessionTimeoutMs = config.groupCoordinatorConfig.classicGroupMinSessionTimeoutMs,
- groupMaxSessionTimeoutMs = config.groupCoordinatorConfig.classicGroupMaxSessionTimeoutMs,
- groupMaxSize = config.groupCoordinatorConfig.classicGroupMaxSize,
- groupInitialRebalanceDelayMs = config.groupCoordinatorConfig.classicGroupInitialRebalanceDelayMs)
-
- val groupMetadataManager = new GroupMetadataManager(config.brokerId, offsetConfig, replicaManager, time, metrics)
- new GroupCoordinator(config.brokerId, groupConfig, offsetConfig, groupMetadataManager, heartbeatPurgatory,
- rebalancePurgatory, time, metrics)
- }
-
- private def memberLeaveError(memberIdentity: MemberIdentity,
- error: Errors): LeaveMemberResponse = {
- LeaveMemberResponse(
- memberId = memberIdentity.memberId,
- groupInstanceId = Option(memberIdentity.groupInstanceId),
- error = error)
- }
-
- private def leaveError(topLevelError: Errors,
- memberResponses: List[LeaveMemberResponse]): LeaveGroupResult = {
- LeaveGroupResult(
- topLevelError = topLevelError,
- memberResponses = memberResponses)
- }
-}
-
-case class GroupConfig(groupMinSessionTimeoutMs: Int,
- groupMaxSessionTimeoutMs: Int,
- groupMaxSize: Int,
- groupInitialRebalanceDelayMs: Int)
-
-case class JoinGroupResult(members: List[JoinGroupResponseMember],
- memberId: String,
- generationId: Int,
- protocolType: Option[String],
- protocolName: Option[String],
- leaderId: String,
- skipAssignment: Boolean,
- error: Errors)
-
-object JoinGroupResult {
- def apply(memberId: String, error: Errors): JoinGroupResult = {
- JoinGroupResult(
- members = List.empty,
- memberId = memberId,
- generationId = GroupCoordinator.NoGeneration,
- protocolType = None,
- protocolName = None,
- leaderId = GroupCoordinator.NoLeader,
- skipAssignment = false,
- error = error)
- }
-}
-
-case class SyncGroupResult(protocolType: Option[String],
- protocolName: Option[String],
- memberAssignment: Array[Byte],
- error: Errors)
-
-object SyncGroupResult {
- def apply(error: Errors): SyncGroupResult = {
- SyncGroupResult(None, None, Array.empty, error)
- }
-}
-
-case class LeaveMemberResponse(memberId: String,
- groupInstanceId: Option[String],
- error: Errors)
-
-case class LeaveGroupResult(topLevelError: Errors,
- memberResponses : List[LeaveMemberResponse])
diff --git a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
deleted file mode 100644
index fd301d14fa2..00000000000
--- a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
+++ /dev/null
@@ -1,690 +0,0 @@
-/**
- * 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 kafka.coordinator.group
-
-import kafka.server.{KafkaConfig, ReplicaManager}
-import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
-import org.apache.kafka.common.message.{ConsumerGroupDescribeResponseData, ConsumerGroupHeartbeatRequestData, ConsumerGroupHeartbeatResponseData, DeleteGroupsResponseData, DescribeGroupsResponseData, DescribeShareGroupOffsetsRequestData, DescribeShareGroupOffsetsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, Offset [...]
-import org.apache.kafka.common.metrics.Metrics
-import org.apache.kafka.common.protocol.{ApiKeys, Errors}
-import org.apache.kafka.common.record.RecordBatch
-import org.apache.kafka.common.requests.{OffsetCommitRequest, RequestContext, TransactionResult}
-import org.apache.kafka.common.utils.{BufferSupplier, Time}
-import org.apache.kafka.coordinator.group
-import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult
-import org.apache.kafka.coordinator.group.OffsetAndMetadata
-import org.apache.kafka.image.{MetadataDelta, MetadataImage}
-import org.apache.kafka.server.common.RequestLocal
-import org.apache.kafka.server.util.FutureUtils
-
-import java.time.Duration
-import java.util
-import java.util.{Optional, OptionalInt, OptionalLong, Properties}
-import java.util.concurrent.CompletableFuture
-import java.util.function.IntSupplier
-import scala.collection.{immutable, mutable}
-import scala.jdk.CollectionConverters._
-
-object GroupCoordinatorAdapter {
- def apply(
- config: KafkaConfig,
- replicaManager: ReplicaManager,
- time: Time,
- metrics: Metrics
- ): GroupCoordinatorAdapter = {
- new GroupCoordinatorAdapter(
- GroupCoordinator(
- config,
- replicaManager,
- time,
- metrics
- ),
- time
- )
- }
-}
-
-/**
- * GroupCoordinatorAdapter is a thin wrapper around kafka.coordinator.group.GroupCoordinator
- * that exposes the new org.apache.kafka.coordinator.group.GroupCoordinator interface.
- */
-private[group] class GroupCoordinatorAdapter(
- private val coordinator: GroupCoordinator,
- private val time: Time
-) extends org.apache.kafka.coordinator.group.GroupCoordinator {
-
- override def consumerGroupHeartbeat(
- context: RequestContext,
- request: ConsumerGroupHeartbeatRequestData
- ): CompletableFuture[ConsumerGroupHeartbeatResponseData] = {
- FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
- s"The old group coordinator does not support ${ApiKeys.CONSUMER_GROUP_HEARTBEAT.name} API."
- ))
- }
-
- override def streamsGroupHeartbeat(
- context: RequestContext,
- request: StreamsGroupHeartbeatRequestData
- ): CompletableFuture[StreamsGroupHeartbeatResult] = {
- FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
- s"The old group coordinator does not support ${ApiKeys.STREAMS_GROUP_HEARTBEAT.name} API."
- ))
- }
-
- override def shareGroupHeartbeat(
- context: RequestContext,
- request: ShareGroupHeartbeatRequestData
- ): CompletableFuture[ShareGroupHeartbeatResponseData] = {
- FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
- s"The old group coordinator does not support ${ApiKeys.SHARE_GROUP_HEARTBEAT.name} API."
- ))
- }
-
- override def describeShareGroupOffsets(
- context: RequestContext,
- request: DescribeShareGroupOffsetsRequestData.DescribeShareGroupOffsetsRequestGroup
- ): CompletableFuture[DescribeShareGroupOffsetsResponseData.DescribeShareGroupOffsetsResponseGroup] = {
- FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
- s"The old group coordinator does not support ${ApiKeys.DESCRIBE_SHARE_GROUP_OFFSETS.name} API."
- ))
- }
-
- override def joinGroup(
- context: RequestContext,
- request: JoinGroupRequestData,
- bufferSupplier: BufferSupplier
- ): CompletableFuture[JoinGroupResponseData] = {
- val future = new CompletableFuture[JoinGroupResponseData]()
-
- def callback(joinResult: JoinGroupResult): Unit = {
- future.complete(new JoinGroupResponseData()
- .setErrorCode(joinResult.error.code)
- .setGenerationId(joinResult.generationId)
- .setProtocolType(joinResult.protocolType.orNull)
- .setProtocolName(joinResult.protocolName.orNull)
- .setLeader(joinResult.leaderId)
- .setSkipAssignment(joinResult.skipAssignment)
- .setMemberId(joinResult.memberId)
- .setMembers(joinResult.members.asJava)
- )
- }
-
- val groupInstanceId = Option(request.groupInstanceId)
-
- // Only return MEMBER_ID_REQUIRED error if joinGroupRequest version is >= 4
- // and groupInstanceId is configured to unknown.
- val requireKnownMemberId = context.apiVersion >= 4 && groupInstanceId.isEmpty
-
- val protocols = request.protocols.valuesList.asScala.map { protocol =>
- (protocol.name, protocol.metadata)
- }.toList
-
- val supportSkippingAssignment = context.apiVersion >= 9
-
- coordinator.handleJoinGroup(
- request.groupId,
- request.memberId,
- groupInstanceId,
- requireKnownMemberId,
- supportSkippingAssignment,
- context.clientId,
- context.clientAddress.toString,
- request.rebalanceTimeoutMs,
- request.sessionTimeoutMs,
- request.protocolType,
- protocols,
- callback,
- Option(request.reason),
- new RequestLocal(bufferSupplier)
- )
-
- future
- }
-
- override def syncGroup(
- context: RequestContext,
- request: SyncGroupRequestData,
- bufferSupplier: BufferSupplier
- ): CompletableFuture[SyncGroupResponseData] = {
- val future = new CompletableFuture[SyncGroupResponseData]()
-
- def callback(syncGroupResult: SyncGroupResult): Unit = {
- future.complete(new SyncGroupResponseData()
- .setErrorCode(syncGroupResult.error.code)
- .setProtocolType(syncGroupResult.protocolType.orNull)
- .setProtocolName(syncGroupResult.protocolName.orNull)
- .setAssignment(syncGroupResult.memberAssignment)
- )
- }
-
- val assignmentMap = immutable.Map.newBuilder[String, Array[Byte]]
- request.assignments.forEach { assignment =>
- assignmentMap += assignment.memberId -> assignment.assignment
- }
-
- coordinator.handleSyncGroup(
- request.groupId,
- request.generationId,
- request.memberId,
- Option(request.protocolType),
- Option(request.protocolName),
- Option(request.groupInstanceId),
- assignmentMap.result(),
- callback,
- new RequestLocal(bufferSupplier)
- )
-
- future
- }
-
- override def heartbeat(
- context: RequestContext,
- request: HeartbeatRequestData
- ): CompletableFuture[HeartbeatResponseData] = {
- val future = new CompletableFuture[HeartbeatResponseData]()
-
- coordinator.handleHeartbeat(
- request.groupId,
- request.memberId,
- Option(request.groupInstanceId),
- request.generationId,
- error => future.complete(new HeartbeatResponseData()
- .setErrorCode(error.code))
- )
-
- future
- }
-
- override def leaveGroup(
- context: RequestContext,
- request: LeaveGroupRequestData
- ): CompletableFuture[LeaveGroupResponseData] = {
- val future = new CompletableFuture[LeaveGroupResponseData]()
-
- def callback(leaveGroupResult: LeaveGroupResult): Unit = {
- future.complete(new LeaveGroupResponseData()
- .setErrorCode(leaveGroupResult.topLevelError.code)
- .setMembers(leaveGroupResult.memberResponses.map { member =>
- new LeaveGroupResponseData.MemberResponse()
- .setErrorCode(member.error.code)
- .setMemberId(member.memberId)
- .setGroupInstanceId(member.groupInstanceId.orNull)
- }.asJava)
- )
- }
-
- coordinator.handleLeaveGroup(
- request.groupId,
- request.members.asScala.toList,
- callback
- )
-
- future
- }
-
- override def listGroups(
- context: RequestContext,
- request: ListGroupsRequestData
- ): CompletableFuture[ListGroupsResponseData] = {
- // Handle a null array the same as empty.
- val (error, groups) = coordinator.handleListGroups(
- Option(request.statesFilter).map(_.asScala.toSet).getOrElse(Set.empty),
- Option(request.typesFilter).map(_.asScala.toSet).getOrElse(Set.empty)
- )
-
- val response = new ListGroupsResponseData()
- .setErrorCode(error.code)
-
- groups.foreach { group =>
- response.groups.add(new ListGroupsResponseData.ListedGroup()
- .setGroupId(group.groupId)
- .setProtocolType(group.protocolType)
- .setGroupState(group.state)
- .setGroupType(group.groupType))
- }
-
- CompletableFuture.completedFuture(response)
- }
-
- override def describeGroups(
- context: RequestContext,
- groupIds: util.List[String]
- ): CompletableFuture[util.List[DescribeGroupsResponseData.DescribedGroup]] = {
-
- def describeGroup(groupId: String): DescribeGroupsResponseData.DescribedGroup = {
- val (error, errorMessage, summary) = coordinator.handleDescribeGroup(groupId, context.apiVersion())
-
- new DescribeGroupsResponseData.DescribedGroup()
- .setErrorCode(error.code)
- .setErrorMessage(errorMessage.orNull)
- .setGroupId(groupId)
- .setGroupState(summary.state)
- .setProtocolType(summary.protocolType)
- .setProtocolData(summary.protocol)
- .setMembers(summary.members.map { member =>
- new DescribeGroupsResponseData.DescribedGroupMember()
- .setMemberId(member.memberId)
- .setGroupInstanceId(member.groupInstanceId.orNull)
- .setClientId(member.clientId)
- .setClientHost(member.clientHost)
- .setMemberAssignment(member.assignment)
- .setMemberMetadata(member.metadata)
- }.asJava)
- }
-
- CompletableFuture.completedFuture(groupIds.asScala.map(describeGroup).asJava)
- }
-
- override def deleteGroups(
- context: RequestContext,
- groupIds: util.List[String],
- bufferSupplier: BufferSupplier
- ): CompletableFuture[DeleteGroupsResponseData.DeletableGroupResultCollection] = {
- val results = new DeleteGroupsResponseData.DeletableGroupResultCollection()
- coordinator.handleDeleteGroups(
- groupIds.asScala.toSet,
- new RequestLocal(bufferSupplier)
- ).foreachEntry { (groupId, error) =>
- results.add(new DeleteGroupsResponseData.DeletableGroupResult()
- .setGroupId(groupId)
- .setErrorCode(error.code))
- }
- CompletableFuture.completedFuture(results)
- }
-
- override def fetchAllOffsets(
- context: RequestContext,
- request: OffsetFetchRequestData.OffsetFetchRequestGroup,
- requireStable: Boolean
- ): CompletableFuture[OffsetFetchResponseData.OffsetFetchResponseGroup] = {
- handleFetchOffset(
- request.groupId,
- requireStable,
- None
- )
- }
-
- override def fetchOffsets(
- context: RequestContext,
- request: OffsetFetchRequestData.OffsetFetchRequestGroup,
- requireStable: Boolean
- ): CompletableFuture[OffsetFetchResponseData.OffsetFetchResponseGroup] = {
- val topicPartitions = new mutable.ArrayBuffer[TopicPartition]()
- request.topics.forEach { topic =>
- topic.partitionIndexes.forEach { partition =>
- topicPartitions += new TopicPartition(topic.name, partition)
- }
- }
-
- handleFetchOffset(
- request.groupId,
- requireStable,
- Some(topicPartitions.toSeq)
- )
- }
-
- private def handleFetchOffset(
- groupId: String,
- requireStable: Boolean,
- partitions: Option[Seq[TopicPartition]]
- ): CompletableFuture[OffsetFetchResponseData.OffsetFetchResponseGroup] = {
- val (error, results) = coordinator.handleFetchOffsets(
- groupId,
- requireStable,
- partitions
- )
-
- val future = new CompletableFuture[OffsetFetchResponseData.OffsetFetchResponseGroup]()
- if (error != Errors.NONE) {
- future.completeExceptionally(error.exception)
- } else {
- val topicsList = new util.ArrayList[OffsetFetchResponseData.OffsetFetchResponseTopics]()
- val topicsMap = new mutable.HashMap[String, OffsetFetchResponseData.OffsetFetchResponseTopics]()
-
- results.foreachEntry { (tp, offset) =>
- val topic = topicsMap.get(tp.topic) match {
- case Some(topic) =>
- topic
-
- case None =>
- val topicOffsets = new OffsetFetchResponseData.OffsetFetchResponseTopics().setName(tp.topic)
- topicsMap += tp.topic -> topicOffsets
- topicsList.add(topicOffsets)
- topicOffsets
- }
-
- topic.partitions.add(new OffsetFetchResponseData.OffsetFetchResponsePartitions()
- .setPartitionIndex(tp.partition)
- .setMetadata(offset.metadata)
- .setCommittedOffset(offset.offset)
- .setCommittedLeaderEpoch(offset.leaderEpoch.orElse(-1))
- .setErrorCode(offset.error.code))
- }
-
- future.complete(new OffsetFetchResponseData.OffsetFetchResponseGroup()
- .setGroupId(groupId)
- .setTopics(topicsList))
- }
-
- future
- }
-
- override def commitOffsets(
- context: RequestContext,
- request: OffsetCommitRequestData,
- bufferSupplier: BufferSupplier
- ): CompletableFuture[OffsetCommitResponseData] = {
- val currentTimeMs = time.milliseconds
- val future = new CompletableFuture[OffsetCommitResponseData]()
-
- def callback(commitStatus: Map[TopicIdPartition, Errors]): Unit = {
- val response = new OffsetCommitResponseData()
- val byTopics = new mutable.HashMap[String, OffsetCommitResponseData.OffsetCommitResponseTopic]()
-
- commitStatus.foreachEntry { (tp, error) =>
- val topic = byTopics.get(tp.topic) match {
- case Some(existingTopic) =>
- existingTopic
- case None =>
- val newTopic = new OffsetCommitResponseData.OffsetCommitResponseTopic().setName(tp.topic)
- byTopics += tp.topic -> newTopic
- response.topics.add(newTopic)
- newTopic
- }
-
- topic.partitions.add(new OffsetCommitResponseData.OffsetCommitResponsePartition()
- .setPartitionIndex(tp.partition)
- .setErrorCode(error.code))
- }
-
- future.complete(response)
- }
-
- // "default" expiration timestamp is defined as now + retention. The retention may be overridden
- // in versions from v2 to v4. Otherwise, the retention defined on the broker is used. If an explicit
- // commit timestamp is provided (v1 only), the expiration timestamp is computed based on that.
- val expireTimeMs = request.retentionTimeMs match {
- case OffsetCommitRequest.DEFAULT_RETENTION_TIME => None
- case retentionTimeMs => Some(currentTimeMs + retentionTimeMs)
- }
-
- val partitions = new mutable.HashMap[TopicIdPartition, OffsetAndMetadata]()
- request.topics.forEach { topic =>
- topic.partitions.forEach { partition =>
- val tp = new TopicIdPartition(Uuid.ZERO_UUID, partition.partitionIndex, topic.name)
- partitions += tp -> createOffsetAndMetadata(
- currentTimeMs,
- partition.committedOffset,
- partition.committedLeaderEpoch,
- partition.committedMetadata,
- expireTimeMs
- )
- }
- }
-
- coordinator.handleCommitOffsets(
- request.groupId,
- request.memberId,
- Option(request.groupInstanceId),
- request.generationIdOrMemberEpoch,
- partitions.toMap,
- callback,
- new RequestLocal(bufferSupplier)
- )
-
- future
- }
-
- override def commitTransactionalOffsets(
- context: RequestContext,
- request: TxnOffsetCommitRequestData,
- bufferSupplier: BufferSupplier
- ): CompletableFuture[TxnOffsetCommitResponseData] = {
- val currentTimeMs = time.milliseconds
- val future = new CompletableFuture[TxnOffsetCommitResponseData]()
-
- def callback(results: Map[TopicIdPartition, Errors]): Unit = {
- val response = new TxnOffsetCommitResponseData()
- val byTopics = new mutable.HashMap[String, TxnOffsetCommitResponseData.TxnOffsetCommitResponseTopic]()
-
- results.foreachEntry { (tp, error) =>
- val topic = byTopics.get(tp.topic) match {
- case Some(existingTopic) =>
- existingTopic
- case None =>
- val newTopic = new TxnOffsetCommitResponseData.TxnOffsetCommitResponseTopic().setName(tp.topic)
- byTopics += tp.topic -> newTopic
- response.topics.add(newTopic)
- newTopic
- }
-
- topic.partitions.add(new TxnOffsetCommitResponseData.TxnOffsetCommitResponsePartition()
- .setPartitionIndex(tp.partition)
- .setErrorCode(error.code))
- }
-
- future.complete(response)
- }
-
- val partitions = new mutable.HashMap[TopicIdPartition, OffsetAndMetadata]()
- request.topics.forEach { topic =>
- topic.partitions.forEach { partition =>
- val tp = new TopicIdPartition(Uuid.ZERO_UUID, partition.partitionIndex, topic.name)
- partitions += tp -> createOffsetAndMetadata(
- currentTimeMs,
- partition.committedOffset,
- partition.committedLeaderEpoch,
- partition.committedMetadata,
- None
- )
- }
- }
-
- coordinator.handleTxnCommitOffsets(
- request.groupId,
- request.transactionalId,
- request.producerId,
- request.producerEpoch,
- request.memberId,
- Option(request.groupInstanceId),
- request.generationId,
- partitions.toMap,
- callback,
- new RequestLocal(bufferSupplier),
- context.apiVersion()
- )
-
- future
- }
-
- private def createOffsetAndMetadata(
- currentTimeMs: Long,
- offset: Long,
- leaderEpoch: Int,
- metadata: String,
- expireTimestamp: Option[Long]
- ): OffsetAndMetadata = {
- new OffsetAndMetadata(
- offset,
- leaderEpoch match {
- case RecordBatch.NO_PARTITION_LEADER_EPOCH => OptionalInt.empty
- case committedLeaderEpoch => OptionalInt.of(committedLeaderEpoch)
- },
- metadata match {
- case null => OffsetAndMetadata.NO_METADATA
- case metadata => metadata
- },
- currentTimeMs,
- expireTimestamp match {
- case Some(timestamp) => OptionalLong.of(timestamp)
- case None => OptionalLong.empty()
- }
- )
- }
-
- override def deleteOffsets(
- context: RequestContext,
- request: OffsetDeleteRequestData,
- bufferSupplier: BufferSupplier
- ): CompletableFuture[OffsetDeleteResponseData] = {
- val future = new CompletableFuture[OffsetDeleteResponseData]()
-
- val partitions = mutable.ArrayBuffer[TopicPartition]()
- request.topics.forEach { topic =>
- topic.partitions.forEach { partition =>
- partitions += new TopicPartition(topic.name, partition.partitionIndex)
- }
- }
-
- val (groupError, topicPartitionResults) = coordinator.handleDeleteOffsets(
- request.groupId,
- partitions,
- new RequestLocal(bufferSupplier)
- )
-
- if (groupError != Errors.NONE) {
- future.completeExceptionally(groupError.exception)
- } else {
- val response = new OffsetDeleteResponseData()
- topicPartitionResults.foreachEntry { (topicPartition, error) =>
- var topic = response.topics.find(topicPartition.topic)
- if (topic == null) {
- topic = new OffsetDeleteResponseData.OffsetDeleteResponseTopic().setName(topicPartition.topic)
- response.topics.add(topic)
- }
- topic.partitions.add(new OffsetDeleteResponseData.OffsetDeleteResponsePartition()
- .setPartitionIndex(topicPartition.partition)
- .setErrorCode(error.code))
- }
-
- future.complete(response)
- }
-
- future
- }
-
- override def completeTransaction(
- tp: TopicPartition,
- producerId: Long,
- producerEpoch: Short,
- coordinatorEpoch: Int,
- result: TransactionResult,
- timeout: Duration
- ): CompletableFuture[Void] = {
- FutureUtils.failedFuture(new IllegalStateException(
- s"The old group coordinator does not support `completeTransaction` API."
- ))
- }
-
- override def partitionFor(groupId: String): Int = {
- coordinator.partitionFor(groupId)
- }
-
- override def onTransactionCompleted(
- producerId: Long,
- partitions: java.lang.Iterable[TopicPartition],
- transactionResult: TransactionResult
- ): CompletableFuture[Void] = {
- try {
- coordinator.scheduleHandleTxnCompletion(
- producerId,
- partitions.asScala,
- transactionResult
- )
- } catch {
- case e: Throwable => FutureUtils.failedFuture(e)
- }
- }
-
- override def onPartitionsDeleted(
- topicPartitions: util.List[TopicPartition],
- bufferSupplier: BufferSupplier
- ): Unit = {
- coordinator.handleDeletedPartitions(topicPartitions.asScala, new RequestLocal(bufferSupplier))
- }
-
- override def onElection(
- groupMetadataPartitionIndex: Int,
- groupMetadataPartitionLeaderEpoch: Int
- ): Unit = {
- coordinator.onElection(groupMetadataPartitionIndex, groupMetadataPartitionLeaderEpoch)
- }
-
- override def onResignation(
- groupMetadataPartitionIndex: Int,
- groupMetadataPartitionLeaderEpoch: OptionalInt
- ): Unit = {
- coordinator.onResignation(groupMetadataPartitionIndex, groupMetadataPartitionLeaderEpoch)
- }
-
- override def onNewMetadataImage(
- newImage: MetadataImage,
- delta: MetadataDelta
- ): Unit = {
- // The metadata image is not used in the old group coordinator.
- }
-
- override def groupMetadataTopicConfigs(): Properties = {
- coordinator.offsetsTopicConfigs
- }
-
- override def groupConfig(groupId: String): Optional[group.GroupConfig] = {
- throw Errors.UNSUPPORTED_VERSION.exception("The old group coordinator does not support get group config.")
- }
-
- override def updateGroupConfig(
- groupId: String,
- newGroupConfig: Properties
- ): Unit = {
- throw Errors.UNSUPPORTED_VERSION.exception("The old group coordinator does not support update group config.")
- }
-
- override def startup(groupMetadataTopicPartitionCount: IntSupplier): Unit = {
- coordinator.startup(() => groupMetadataTopicPartitionCount.getAsInt)
- }
-
- override def shutdown(): Unit = {
- coordinator.shutdown()
- }
-
- override def consumerGroupDescribe(
- context: RequestContext,
- groupIds: util.List[String]
- ): CompletableFuture[util.List[ConsumerGroupDescribeResponseData.DescribedGroup]] = {
- FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
- s"The old group coordinator does not support ${ApiKeys.CONSUMER_GROUP_DESCRIBE.name} API."
- ))
- }
-
- override def streamsGroupDescribe(
- context: RequestContext,
- groupIds: util.List[String]
- ): CompletableFuture[util.List[StreamsGroupDescribeResponseData.DescribedGroup]] = {
- FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
- s"The old group coordinator does not support ${ApiKeys.STREAMS_GROUP_DESCRIBE.name} API."
- ))
- }
-
- override def shareGroupDescribe(
- context: RequestContext,
- groupIds: util.List[String]
- ): CompletableFuture[util.List[ShareGroupDescribeResponseData.DescribedGroup]] = {
- FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
- s"The old group coordinator does not support ${ApiKeys.SHARE_GROUP_DESCRIBE.name} API."
- ))
- }
-}
diff --git a/core/src/main/scala/kafka/coordinator/group/GroupMetadata.scala b/core/src/main/scala/kafka/coordinator/group/GroupMetadata.scala
deleted file mode 100644
index 2f73577a5dd..00000000000
--- a/core/src/main/scala/kafka/coordinator/group/GroupMetadata.scala
+++ /dev/null
@@ -1,857 +0,0 @@
-/*
- * 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 kafka.coordinator.group
-
-import java.nio.ByteBuffer
-import java.util.UUID
-import java.util.concurrent.locks.ReentrantLock
-import kafka.utils.{CoreUtils, Logging, nonthreadsafe}
-import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
-import org.apache.kafka.common.{TopicIdPartition, TopicPartition}
-import org.apache.kafka.common.message.JoinGroupResponseData.JoinGroupResponseMember
-import org.apache.kafka.common.protocol.Errors
-import org.apache.kafka.common.protocol.types.SchemaException
-import org.apache.kafka.common.utils.Time
-import org.apache.kafka.coordinator.group.{Group, OffsetAndMetadata}
-
-import scala.collection.{Seq, immutable, mutable}
-import scala.jdk.CollectionConverters._
-
-private[group] sealed trait GroupState {
- val validPreviousStates: Set[GroupState]
- val toLowerCaseString: String = toString.toLowerCase
-}
-
-/**
- * Group is preparing to rebalance
- *
- * action: respond to heartbeats with REBALANCE_IN_PROGRESS
- * respond to sync group with REBALANCE_IN_PROGRESS
- * remove member on leave group request
- * park join group requests from new or existing members until all expected members have joined
- * allow offset commits from previous generation
- * allow offset fetch requests
- * transition: some members have joined by the timeout => CompletingRebalance
- * all members have left the group => Empty
- * group is removed by partition emigration => Dead
- */
-private[group] case object PreparingRebalance extends GroupState {
- val validPreviousStates: Set[GroupState] = Set(Stable, CompletingRebalance, Empty)
-}
-
-/**
- * Group is awaiting state assignment from the leader
- *
- * action: respond to heartbeats with REBALANCE_IN_PROGRESS
- * respond to offset commits with REBALANCE_IN_PROGRESS
- * park sync group requests from followers until transition to Stable
- * allow offset fetch requests
- * transition: sync group with state assignment received from leader => Stable
- * join group from new member or existing member with updated metadata => PreparingRebalance
- * leave group from existing member => PreparingRebalance
- * member failure detected => PreparingRebalance
- * group is removed by partition emigration => Dead
- */
-private[group] case object CompletingRebalance extends GroupState {
- val validPreviousStates: Set[GroupState] = Set(PreparingRebalance)
-}
-
-/**
- * Group is stable
- *
- * action: respond to member heartbeats normally
- * respond to sync group from any member with current assignment
- * respond to join group from followers with matching metadata with current group metadata
- * allow offset commits from member of current generation
- * allow offset fetch requests
- * transition: member failure detected via heartbeat => PreparingRebalance
- * leave group from existing member => PreparingRebalance
- * leader join-group received => PreparingRebalance
- * follower join-group with new metadata => PreparingRebalance
- * group is removed by partition emigration => Dead
- */
-private[group] case object Stable extends GroupState {
- val validPreviousStates: Set[GroupState] = Set(CompletingRebalance)
-}
-
-/**
- * Group has no more members and its metadata is being removed
- *
- * action: respond to join group with UNKNOWN_MEMBER_ID
- * respond to sync group with UNKNOWN_MEMBER_ID
- * respond to heartbeat with UNKNOWN_MEMBER_ID
- * respond to leave group with UNKNOWN_MEMBER_ID
- * respond to offset commit with UNKNOWN_MEMBER_ID
- * allow offset fetch requests
- * transition: Dead is a final state before group metadata is cleaned up, so there are no transitions
- */
-private[group] case object Dead extends GroupState {
- val validPreviousStates: Set[GroupState] = Set(Stable, PreparingRebalance, CompletingRebalance, Empty, Dead)
-}
-
-/**
- * Group has no more members, but lingers until all offsets have expired. This state
- * also represents groups which use Kafka only for offset commits and have no members.
- *
- * action: respond normally to join group from new members
- * respond to sync group with UNKNOWN_MEMBER_ID
- * respond to heartbeat with UNKNOWN_MEMBER_ID
- * respond to leave group with UNKNOWN_MEMBER_ID
- * respond to offset commit with UNKNOWN_MEMBER_ID
- * allow offset fetch requests
- * transition: last offsets removed in periodic expiration task => Dead
- * join group from a new member => PreparingRebalance
- * group is removed by partition emigration => Dead
- * group is removed by expiration => Dead
- */
-private[group] case object Empty extends GroupState {
- val validPreviousStates: Set[GroupState] = Set(PreparingRebalance)
-}
-
-
-private object GroupMetadata extends Logging {
-
- def loadGroup(groupId: String,
- initialState: GroupState,
- generationId: Int,
- protocolType: String,
- protocolName: String,
- leaderId: String,
- currentStateTimestamp: Option[Long],
- members: Iterable[MemberMetadata],
- time: Time): GroupMetadata = {
- val group = new GroupMetadata(groupId, initialState, time)
- group.generationId = generationId
- group.protocolType = if (protocolType == null || protocolType.isEmpty) None else Some(protocolType)
- group.protocolName = Option(protocolName)
- group.leaderId = Option(leaderId)
- group.currentStateTimestamp = currentStateTimestamp
- members.foreach { member =>
- group.add(member, null)
- info(s"Loaded member $member in group $groupId with generation ${group.generationId}.")
- }
- group.subscribedTopics = group.computeSubscribedTopics()
- group
- }
-
- private val MemberIdDelimiter = "-"
-}
-
-/**
- * Case class used to represent group metadata for the ListGroups API
- */
-case class GroupOverview(groupId: String,
- protocolType: String,
- state: String,
- groupType: String)
-
-/**
- * Case class used to represent group metadata for the DescribeGroup API
- */
-case class GroupSummary(state: String,
- protocolType: String,
- protocol: String,
- members: List[MemberSummary])
-
-/**
- * We cache offset commits along with their commit record offset. This enables us to ensure that the latest offset
- * commit is always materialized when we have a mix of transactional and regular offset commits. Without preserving
- * information of the commit record offset, compaction of the offsets topic itself may result in the wrong offset commit
- * being materialized.
- */
-case class CommitRecordMetadataAndOffset(appendedBatchOffset: Option[Long], offsetAndMetadata: OffsetAndMetadata) {
- def olderThan(that: CommitRecordMetadataAndOffset): Boolean = appendedBatchOffset.get < that.appendedBatchOffset.get
-}
-
-/**
- * Group contains the following metadata:
- *
- * Membership metadata:
- * 1. Members registered in this group
- * 2. Current protocol assigned to the group (e.g. partition assignment strategy for consumers)
- * 3. Protocol metadata associated with group members
- *
- * State metadata:
- * 1. group state
- * 2. generation id
- * 3. leader id
- */
-@nonthreadsafe
-private[group] class GroupMetadata(val groupId: String, initialState: GroupState, time: Time) extends Logging {
- type JoinCallback = JoinGroupResult => Unit
-
- private[group] val lock = new ReentrantLock
-
- private var state: GroupState = initialState
- var currentStateTimestamp: Option[Long] = Some(time.milliseconds())
- var protocolType: Option[String] = None
- var protocolName: Option[String] = None
- var generationId = 0
- private var leaderId: Option[String] = None
-
- private val members = new mutable.HashMap[String, MemberMetadata]
- // Static membership mapping [key: group.instance.id, value: member.id]
- private val staticMembers = new mutable.HashMap[String, String]
- private val pendingMembers = new mutable.HashSet[String]
- private var numMembersAwaitingJoin = 0
- private val supportedProtocols = new mutable.HashMap[String, Integer]().withDefaultValue(0)
- private val offsets = new mutable.HashMap[TopicPartition, CommitRecordMetadataAndOffset]
- private val pendingOffsetCommits = new mutable.HashMap[TopicPartition, OffsetAndMetadata]
- private val pendingTransactionalOffsetCommits = new mutable.HashMap[Long, mutable.Map[TopicPartition, CommitRecordMetadataAndOffset]]()
- private var receivedTransactionalOffsetCommits = false
- private var receivedConsumerOffsetCommits = false
- private val pendingSyncMembers = new mutable.HashSet[String]
-
- // When protocolType == `consumer`, a set of subscribed topics is maintained. The set is
- // computed when a new generation is created or when the group is restored from the log.
- private var subscribedTopics: Option[Set[String]] = None
-
- var newMemberAdded: Boolean = false
-
- def inLock[T](fun: => T): T = CoreUtils.inLock(lock)(fun)
-
- def is(groupState: GroupState): Boolean = state == groupState
- def has(memberId: String): Boolean = members.contains(memberId)
- def get(memberId: String): MemberMetadata = members(memberId)
- def size: Int = members.size
-
- def isLeader(memberId: String): Boolean = leaderId.contains(memberId)
- def leaderOrNull: String = leaderId.orNull
- def currentStateTimestampOrDefault: Long = currentStateTimestamp.getOrElse(-1)
-
- def isConsumerGroup: Boolean = protocolType.contains(ConsumerProtocol.PROTOCOL_TYPE)
-
- def add(member: MemberMetadata, callback: JoinCallback = null): Unit = {
- member.groupInstanceId.foreach { instanceId =>
- if (staticMembers.contains(instanceId))
- throw new IllegalStateException(s"Static member with groupInstanceId=$instanceId " +
- s"cannot be added to group $groupId since it is already a member")
- staticMembers.put(instanceId, member.memberId)
- }
-
- if (members.isEmpty)
- this.protocolType = Some(member.protocolType)
-
- assert(this.protocolType.orNull == member.protocolType)
- assert(supportsProtocols(member.protocolType, MemberMetadata.plainProtocolSet(member.supportedProtocols)))
-
- if (leaderId.isEmpty)
- leaderId = Some(member.memberId)
-
- members.put(member.memberId, member)
- incSupportedProtocols(member)
- member.awaitingJoinCallback = callback
-
- if (member.isAwaitingJoin)
- numMembersAwaitingJoin += 1
-
- pendingMembers.remove(member.memberId)
- }
-
- def remove(memberId: String): Unit = {
- members.remove(memberId).foreach { member =>
- decSupportedProtocols(member)
- if (member.isAwaitingJoin)
- numMembersAwaitingJoin -= 1
-
- member.groupInstanceId.foreach(staticMembers.remove)
- }
-
- if (isLeader(memberId))
- leaderId = members.keys.headOption
-
- pendingMembers.remove(memberId)
- pendingSyncMembers.remove(memberId)
- }
-
- /**
- * Check whether current leader is rejoined. If not, try to find another joined member to be
- * new leader. Return false if
- * 1. the group is currently empty (has no designated leader)
- * 2. no member rejoined
- */
- def maybeElectNewJoinedLeader(): Boolean = {
- leaderId.exists { currentLeaderId =>
- val currentLeader = get(currentLeaderId)
- if (!currentLeader.isAwaitingJoin) {
- members.find(_._2.isAwaitingJoin) match {
- case Some((anyJoinedMemberId, anyJoinedMember)) =>
- leaderId = Option(anyJoinedMemberId)
- info(s"Group leader [member.id: ${currentLeader.memberId}, " +
- s"group.instance.id: ${currentLeader.groupInstanceId}] failed to join " +
- s"before rebalance timeout, while new leader $anyJoinedMember was elected.")
- true
-
- case None =>
- info(s"Group leader [member.id: ${currentLeader.memberId}, " +
- s"group.instance.id: ${currentLeader.groupInstanceId}] failed to join " +
- s"before rebalance timeout, and the group couldn't proceed to next generation" +
- s"because no member joined.")
- false
- }
- } else {
- true
- }
- }
- }
-
- /**
- * [For static members only]: Replace the old member id with the new one,
- * keep everything else unchanged and return the updated member.
- */
- def replaceStaticMember(
- groupInstanceId: String,
- oldMemberId: String,
- newMemberId: String
- ): MemberMetadata = {
- val memberMetadata = members.remove(oldMemberId)
- .getOrElse(throw new IllegalArgumentException(s"Cannot replace non-existing member id $oldMemberId"))
-
- // Fence potential duplicate member immediately if someone awaits join/sync callback.
- maybeInvokeJoinCallback(memberMetadata, JoinGroupResult(oldMemberId, Errors.FENCED_INSTANCE_ID))
- maybeInvokeSyncCallback(memberMetadata, SyncGroupResult(Errors.FENCED_INSTANCE_ID))
-
- memberMetadata.memberId = newMemberId
- members.put(newMemberId, memberMetadata)
-
- if (isLeader(oldMemberId)) {
- leaderId = Some(newMemberId)
- }
-
- staticMembers.put(groupInstanceId, newMemberId)
- memberMetadata
- }
-
- def isPendingMember(memberId: String): Boolean = pendingMembers.contains(memberId)
-
- def addPendingMember(memberId: String): Boolean = {
- if (has(memberId)) {
- throw new IllegalStateException(s"Attempt to add pending member $memberId which is already " +
- s"a stable member of the group")
- }
- pendingMembers.add(memberId)
- }
-
- def addPendingSyncMember(memberId: String): Boolean = {
- if (!has(memberId)) {
- throw new IllegalStateException(s"Attempt to add a pending sync for member $memberId which " +
- "is not a member of the group")
- }
- pendingSyncMembers.add(memberId)
- }
-
- def removePendingSyncMember(memberId: String): Boolean = {
- if (!has(memberId)) {
- throw new IllegalStateException(s"Attempt to remove a pending sync for member $memberId which " +
- "is not a member of the group")
- }
- pendingSyncMembers.remove(memberId)
- }
-
- def hasReceivedSyncFromAllMembers: Boolean = {
- pendingSyncMembers.isEmpty
- }
-
- def allPendingSyncMembers: Set[String] = {
- pendingSyncMembers.toSet
- }
-
- def clearPendingSyncMembers(): Unit = {
- pendingSyncMembers.clear()
- }
-
- def hasStaticMember(groupInstanceId: String): Boolean = {
- staticMembers.contains(groupInstanceId)
- }
-
- def currentStaticMemberId(groupInstanceId: String): Option[String] = {
- staticMembers.get(groupInstanceId)
- }
-
- def currentState: GroupState = state
-
- def notYetRejoinedMembers: Map[String, MemberMetadata] = members.filterNot(_._2.isAwaitingJoin).toMap
-
- def hasAllMembersJoined: Boolean = members.size == numMembersAwaitingJoin && pendingMembers.isEmpty
-
- def allMembers: collection.Set[String] = members.keySet
-
- def allStaticMembers: collection.Set[String] = staticMembers.keySet
-
- // For testing only.
- private[group] def allDynamicMembers: Set[String] = {
- val dynamicMemberSet = new mutable.HashSet[String]
- allMembers.foreach(memberId => dynamicMemberSet.add(memberId))
- staticMembers.values.foreach(memberId => dynamicMemberSet.remove(memberId))
- dynamicMemberSet.toSet
- }
-
- def numPending: Int = pendingMembers.size
-
- def numAwaiting: Int = numMembersAwaitingJoin
-
- def allMemberMetadata: List[MemberMetadata] = members.values.toList
-
- def rebalanceTimeoutMs: Int = members.values.foldLeft(0) { (timeout, member) =>
- timeout.max(member.rebalanceTimeoutMs)
- }
-
- def generateMemberId(clientId: String,
- groupInstanceId: Option[String]): String = {
- groupInstanceId match {
- case None =>
- clientId + GroupMetadata.MemberIdDelimiter + UUID.randomUUID().toString
- case Some(instanceId) =>
- instanceId + GroupMetadata.MemberIdDelimiter + UUID.randomUUID().toString
- }
- }
-
- def canRebalance: Boolean = PreparingRebalance.validPreviousStates.contains(state)
-
- def transitionTo(groupState: GroupState): Unit = {
- assertValidTransition(groupState)
- state = groupState
- currentStateTimestamp = Some(time.milliseconds())
- }
-
- def selectProtocol: String = {
- if (members.isEmpty)
- throw new IllegalStateException("Cannot select protocol for empty group")
-
- // select the protocol for this group which is supported by all members
- val candidates = candidateProtocols
-
- // let each member vote for one of the protocols and choose the one with the most votes
- val (protocol, _) = allMemberMetadata
- .map(_.vote(candidates))
- .groupBy(identity)
- .maxBy { case (_, votes) => votes.size }
-
- protocol
- }
-
- private def incSupportedProtocols(member: MemberMetadata): Unit = {
- member.supportedProtocols.foreach { case (protocol, _) => supportedProtocols(protocol) += 1 }
- }
-
- private def decSupportedProtocols(member: MemberMetadata): Unit = {
- member.supportedProtocols.foreach { case (protocol, _) => supportedProtocols(protocol) -= 1 }
- }
-
- private def candidateProtocols: Set[String] = {
- // get the set of protocols that are commonly supported by all members
- val numMembers = members.size
- supportedProtocols.filter(_._2 == numMembers).keys.toSet
- }
-
- def supportsProtocols(memberProtocolType: String, memberProtocols: Set[String]): Boolean = {
- if (is(Empty))
- memberProtocolType.nonEmpty && memberProtocols.nonEmpty
- else
- protocolType.contains(memberProtocolType) && memberProtocols.exists(supportedProtocols(_) == members.size)
- }
-
- def getSubscribedTopics: Option[Set[String]] = subscribedTopics
-
- /**
- * Returns true if the consumer group is actively subscribed to the topic. When the consumer
- * group does not know, because the information is not available yet or because the it has
- * failed to parse the Consumer Protocol, it returns true to be safe.
- */
- def isSubscribedToTopic(topic: String): Boolean = subscribedTopics match {
- case Some(topics) => topics.contains(topic)
- case None => true
- }
-
- /**
- * Collects the set of topics that the members are subscribed to when the Protocol Type is equal
- * to 'consumer'. None is returned if
- * - the protocol type is not equal to 'consumer';
- * - the protocol is not defined yet; or
- * - the protocol metadata does not comply with the schema.
- */
- private[group] def computeSubscribedTopics(): Option[Set[String]] = {
- protocolType match {
- case Some(ConsumerProtocol.PROTOCOL_TYPE) if members.nonEmpty && protocolName.isDefined =>
- try {
- Some(
- members.map { case (_, member) =>
- // The consumer protocol is parsed with V0 which is the based prefix of all versions.
- // This way the consumer group manager does not depend on any specific existing or
- // future versions of the consumer protocol. VO must prefix all new versions.
- val buffer = ByteBuffer.wrap(member.metadata(protocolName.get))
- ConsumerProtocol.deserializeVersion(buffer)
- ConsumerProtocol.deserializeSubscription(buffer, 0).topics.asScala.toSet
- }.reduceLeft(_ ++ _)
- )
- } catch {
- case e: SchemaException =>
- warn(s"Failed to parse Consumer Protocol ${ConsumerProtocol.PROTOCOL_TYPE}:${protocolName.get} " +
- s"of group $groupId. Consumer group coordinator is not aware of the subscribed topics.", e)
- None
- }
-
- case Some(ConsumerProtocol.PROTOCOL_TYPE) if members.isEmpty =>
- Option(Set.empty)
-
- case _ => None
- }
- }
-
- def updateMember(member: MemberMetadata,
- protocols: List[(String, Array[Byte])],
- rebalanceTimeoutMs: Int,
- sessionTimeoutMs: Int,
- callback: JoinCallback): Unit = {
- decSupportedProtocols(member)
- member.supportedProtocols = protocols
- incSupportedProtocols(member)
- member.rebalanceTimeoutMs = rebalanceTimeoutMs
- member.sessionTimeoutMs = sessionTimeoutMs
-
- if (callback != null && !member.isAwaitingJoin) {
- numMembersAwaitingJoin += 1
- } else if (callback == null && member.isAwaitingJoin) {
- numMembersAwaitingJoin -= 1
- }
- member.awaitingJoinCallback = callback
- }
-
- def maybeInvokeJoinCallback(member: MemberMetadata,
- joinGroupResult: JoinGroupResult): Unit = {
- if (member.isAwaitingJoin) {
- try {
- member.awaitingJoinCallback(joinGroupResult)
- } catch {
- case t: Throwable =>
- error(s"Failed to invoke join callback for $member due to ${t.getMessage}.", t)
- member.awaitingJoinCallback(JoinGroupResult(member.memberId, Errors.UNKNOWN_SERVER_ERROR))
- } finally {
- member.awaitingJoinCallback = null
- numMembersAwaitingJoin -= 1
- }
- }
- }
-
- /**
- * @return true if a sync callback actually performs.
- */
- def maybeInvokeSyncCallback(member: MemberMetadata,
- syncGroupResult: SyncGroupResult): Boolean = {
- if (member.isAwaitingSync) {
- try {
- member.awaitingSyncCallback(syncGroupResult)
- } catch {
- case t: Throwable =>
- error(s"Failed to invoke sync callback for $member due to ${t.getMessage}.", t)
- member.awaitingSyncCallback(SyncGroupResult(Errors.UNKNOWN_SERVER_ERROR))
- } finally {
- member.awaitingSyncCallback = null
- }
- true
- } else {
- false
- }
- }
-
- def initNextGeneration(): Unit = {
- if (members.nonEmpty) {
- generationId += 1
- protocolName = Some(selectProtocol)
- subscribedTopics = computeSubscribedTopics()
- transitionTo(CompletingRebalance)
- } else {
- generationId += 1
- protocolName = None
- subscribedTopics = computeSubscribedTopics()
- transitionTo(Empty)
- }
- receivedConsumerOffsetCommits = false
- receivedTransactionalOffsetCommits = false
- clearPendingSyncMembers()
- }
-
- def currentMemberMetadata: List[JoinGroupResponseMember] = {
- if (is(Dead) || is(PreparingRebalance))
- throw new IllegalStateException("Cannot obtain member metadata for group in state %s".format(state))
- members.map{ case (memberId, memberMetadata) => new JoinGroupResponseMember()
- .setMemberId(memberId)
- .setGroupInstanceId(memberMetadata.groupInstanceId.orNull)
- .setMetadata(memberMetadata.metadata(protocolName.get))
- }.toList
- }
-
- def summary: GroupSummary = {
- if (is(Stable)) {
- val protocol = protocolName.orNull
- if (protocol == null)
- throw new IllegalStateException("Invalid null group protocol for stable group")
-
- val members = this.members.values.map { member => member.summary(protocol) }
- GroupSummary(state.toString, protocolType.getOrElse(""), protocol, members.toList)
- } else {
- val members = this.members.values.map{ member => member.summaryNoMetadata() }
- GroupSummary(state.toString, protocolType.getOrElse(""), GroupCoordinator.NoProtocol, members.toList)
- }
- }
-
- def overview: GroupOverview = {
- GroupOverview(groupId, protocolType.getOrElse(""), state.toString, Group.GroupType.CLASSIC.toString)
- }
-
- def initializeOffsets(offsets: collection.Map[TopicPartition, CommitRecordMetadataAndOffset],
- pendingTxnOffsets: Map[Long, mutable.Map[TopicPartition, CommitRecordMetadataAndOffset]]): Unit = {
- this.offsets ++= offsets
- this.pendingTransactionalOffsetCommits ++= pendingTxnOffsets
- }
-
- def onOffsetCommitAppend(topicIdPartition: TopicIdPartition, offsetWithCommitRecordMetadata: CommitRecordMetadataAndOffset): Unit = {
- val topicPartition = topicIdPartition.topicPartition
- if (pendingOffsetCommits.contains(topicPartition)) {
- if (offsetWithCommitRecordMetadata.appendedBatchOffset.isEmpty)
- throw new IllegalStateException("Cannot complete offset commit write without providing the metadata of the record " +
- "in the log.")
- if (!offsets.contains(topicPartition) || offsets(topicPartition).olderThan(offsetWithCommitRecordMetadata))
- offsets.put(topicPartition, offsetWithCommitRecordMetadata)
- }
-
- pendingOffsetCommits.get(topicPartition) match {
- case Some(stagedOffset) if offsetWithCommitRecordMetadata.offsetAndMetadata == stagedOffset =>
- pendingOffsetCommits.remove(topicPartition)
- case _ =>
- // The pendingOffsetCommits for this partition could be empty if the topic was deleted, in which case
- // its entries would be removed from the cache by the `removeOffsets` method.
- }
- }
-
- def failPendingOffsetWrite(topicIdPartition: TopicIdPartition, offset: OffsetAndMetadata): Unit = {
- val topicPartition = topicIdPartition.topicPartition
- pendingOffsetCommits.get(topicPartition) match {
- case Some(pendingOffset) if offset == pendingOffset => pendingOffsetCommits.remove(topicPartition)
- case _ =>
- }
- }
-
- def prepareOffsetCommit(offsets: Map[TopicIdPartition, OffsetAndMetadata]): Unit = {
- receivedConsumerOffsetCommits = true
- offsets.foreachEntry { (topicIdPartition, offsetAndMetadata) =>
- pendingOffsetCommits += topicIdPartition.topicPartition -> offsetAndMetadata
- }
- }
-
- def prepareTxnOffsetCommit(producerId: Long, offsets: Map[TopicIdPartition, OffsetAndMetadata]): Unit = {
- trace(s"TxnOffsetCommit for producer $producerId and group $groupId with offsets $offsets is pending")
- receivedTransactionalOffsetCommits = true
- val producerOffsets = pendingTransactionalOffsetCommits.getOrElseUpdate(producerId,
- mutable.Map.empty[TopicPartition, CommitRecordMetadataAndOffset])
-
- offsets.foreachEntry { (topicIdPartition, offsetAndMetadata) =>
- producerOffsets.put(topicIdPartition.topicPartition, CommitRecordMetadataAndOffset(None, offsetAndMetadata))
- }
- }
-
- def hasReceivedConsistentOffsetCommits : Boolean = {
- !receivedConsumerOffsetCommits || !receivedTransactionalOffsetCommits
- }
-
- /* Remove a pending transactional offset commit if the actual offset commit record was not written to the log.
- * We will return an error and the client will retry the request, potentially to a different coordinator.
- */
- def failPendingTxnOffsetCommit(producerId: Long, topicIdPartition: TopicIdPartition): Unit = {
- val topicPartition = topicIdPartition.topicPartition
- pendingTransactionalOffsetCommits.get(producerId) match {
- case Some(pendingOffsets) =>
- val pendingOffsetCommit = pendingOffsets.remove(topicPartition)
- trace(s"TxnOffsetCommit for producer $producerId and group $groupId with offsets $pendingOffsetCommit failed " +
- s"to be appended to the log")
- if (pendingOffsets.isEmpty)
- pendingTransactionalOffsetCommits.remove(producerId)
- case _ =>
- // We may hit this case if the partition in question has emigrated already.
- }
- }
-
- def onTxnOffsetCommitAppend(producerId: Long, topicIdPartition: TopicIdPartition,
- commitRecordMetadataAndOffset: CommitRecordMetadataAndOffset): Unit = {
- val topicPartition = topicIdPartition.topicPartition
- pendingTransactionalOffsetCommits.get(producerId) match {
- case Some(pendingOffset) =>
- if (pendingOffset.contains(topicPartition)
- && pendingOffset(topicPartition).offsetAndMetadata == commitRecordMetadataAndOffset.offsetAndMetadata)
- pendingOffset.update(topicPartition, commitRecordMetadataAndOffset)
- case _ =>
- // We may hit this case if the partition in question has emigrated.
- }
- }
-
- /* Complete a pending transactional offset commit. This is called after a commit or abort marker is fully written
- * to the log.
- */
- def completePendingTxnOffsetCommit(producerId: Long, isCommit: Boolean): Unit = {
- val pendingOffsetsOpt = pendingTransactionalOffsetCommits.remove(producerId)
- if (isCommit) {
- pendingOffsetsOpt.foreach { pendingOffsets =>
- pendingOffsets.foreachEntry { (topicPartition, commitRecordMetadataAndOffset) =>
- if (commitRecordMetadataAndOffset.appendedBatchOffset.isEmpty)
- throw new IllegalStateException(s"Trying to complete a transactional offset commit for producerId $producerId " +
- s"and groupId $groupId even though the offset commit record itself hasn't been appended to the log.")
-
- val currentOffsetOpt = offsets.get(topicPartition)
- if (currentOffsetOpt.forall(_.olderThan(commitRecordMetadataAndOffset))) {
- trace(s"TxnOffsetCommit for producer $producerId and group $groupId with offset $commitRecordMetadataAndOffset " +
- "committed and loaded into the cache.")
- offsets.put(topicPartition, commitRecordMetadataAndOffset)
- } else {
- trace(s"TxnOffsetCommit for producer $producerId and group $groupId with offset $commitRecordMetadataAndOffset " +
- s"committed, but not loaded since its offset is older than current offset $currentOffsetOpt.")
- }
- }
- }
- } else {
- trace(s"TxnOffsetCommit for producer $producerId and group $groupId with offsets $pendingOffsetsOpt aborted")
- }
- }
-
- def activeProducers: collection.Set[Long] = pendingTransactionalOffsetCommits.keySet
-
- def hasPendingOffsetCommitsFromProducer(producerId: Long): Boolean =
- pendingTransactionalOffsetCommits.contains(producerId)
-
- def hasPendingOffsetCommitsForTopicPartition(topicPartition: TopicPartition): Boolean = {
- pendingOffsetCommits.contains(topicPartition) ||
- pendingTransactionalOffsetCommits.exists(
- _._2.contains(topicPartition)
- )
- }
-
- def removeAllOffsets(): immutable.Map[TopicPartition, OffsetAndMetadata] = removeOffsets(offsets.keySet.toSeq)
-
- def removeOffsets(topicPartitions: Seq[TopicPartition]): immutable.Map[TopicPartition, OffsetAndMetadata] = {
- topicPartitions.flatMap { topicPartition =>
- pendingOffsetCommits.remove(topicPartition)
- pendingTransactionalOffsetCommits.foreachEntry { (_, pendingOffsets) =>
- pendingOffsets.remove(topicPartition)
- }
- val removedOffset = offsets.remove(topicPartition)
- removedOffset.map(topicPartition -> _.offsetAndMetadata)
- }.toMap
- }
-
- def removeExpiredOffsets(currentTimestamp: Long, offsetRetentionMs: Long): Map[TopicPartition, OffsetAndMetadata] = {
-
- def getExpiredOffsets(baseTimestamp: CommitRecordMetadataAndOffset => Long,
- subscribedTopics: Set[String] = Set.empty): Map[TopicPartition, OffsetAndMetadata] = {
- offsets.filter {
- case (topicPartition, commitRecordMetadataAndOffset) =>
- !subscribedTopics.contains(topicPartition.topic()) &&
- !pendingOffsetCommits.contains(topicPartition) && {
- if (commitRecordMetadataAndOffset.offsetAndMetadata.expireTimestampMs.isEmpty) {
- // current version with no per partition retention
- currentTimestamp - baseTimestamp(commitRecordMetadataAndOffset) >= offsetRetentionMs
- } else {
- // older versions with explicit expire_timestamp field => old expiration semantics is used
- currentTimestamp >= commitRecordMetadataAndOffset.offsetAndMetadata.expireTimestampMs.getAsLong
- }
- }
- }.map {
- case (topicPartition, commitRecordOffsetAndMetadata) =>
- (topicPartition, commitRecordOffsetAndMetadata.offsetAndMetadata)
- }.toMap
- }
-
- val expiredOffsets: Map[TopicPartition, OffsetAndMetadata] = protocolType match {
- case Some(_) if is(Empty) =>
- // no consumer exists in the group =>
- // - if current state timestamp exists and retention period has passed since group became Empty,
- // expire all offsets with no pending offset commit;
- // - if there is no current state timestamp (old group metadata schema) and retention period has passed
- // since the last commit timestamp, expire the offset
- getExpiredOffsets(
- commitRecordMetadataAndOffset => currentStateTimestamp
- .getOrElse(commitRecordMetadataAndOffset.offsetAndMetadata.commitTimestampMs)
- )
-
- case Some(ConsumerProtocol.PROTOCOL_TYPE) if subscribedTopics.isDefined && is(Stable) =>
- // consumers exist in the group and group is stable =>
- // - if the group is aware of the subscribed topics and retention period had passed since the
- // the last commit timestamp, expire the offset. offset with pending offset commit are not
- // expired
- getExpiredOffsets(
- _.offsetAndMetadata.commitTimestampMs,
- subscribedTopics.get
- )
-
- case None =>
- // protocolType is None => standalone (simple) consumer, that uses Kafka for offset storage only
- // expire offsets with no pending offset commit that retention period has passed since their last commit
- getExpiredOffsets(_.offsetAndMetadata.commitTimestampMs)
-
- case _ =>
- Map()
- }
-
- if (expiredOffsets.nonEmpty)
- debug(s"Expired offsets from group '$groupId': ${expiredOffsets.keySet}")
-
- offsets --= expiredOffsets.keySet
- expiredOffsets
- }
-
- def allOffsets: Map[TopicPartition, OffsetAndMetadata] = offsets.map { case (topicPartition, commitRecordMetadataAndOffset) =>
- (topicPartition, commitRecordMetadataAndOffset.offsetAndMetadata)
- }.toMap
-
- def offset(topicPartition: TopicPartition): Option[OffsetAndMetadata] = offsets.get(topicPartition).map(_.offsetAndMetadata)
-
- // visible for testing
- private[group] def offsetWithRecordMetadata(topicPartition: TopicPartition): Option[CommitRecordMetadataAndOffset] = offsets.get(topicPartition)
-
- // Used for testing
- private[group] def pendingOffsetCommit(topicIdPartition: TopicIdPartition): Option[OffsetAndMetadata] = {
- pendingOffsetCommits.get(topicIdPartition.topicPartition)
- }
-
- // Used for testing
- private[group] def pendingTxnOffsetCommit(producerId: Long, topicIdPartition: TopicIdPartition): Option[CommitRecordMetadataAndOffset] = {
- pendingTransactionalOffsetCommits.get(producerId).flatMap(_.get(topicIdPartition.topicPartition))
- }
-
- def numOffsets: Int = offsets.size
-
- def hasOffsets: Boolean = offsets.nonEmpty || pendingOffsetCommits.nonEmpty || pendingTransactionalOffsetCommits.nonEmpty
-
- private def assertValidTransition(targetState: GroupState): Unit = {
- if (!targetState.validPreviousStates.contains(state))
- throw new IllegalStateException("Group %s should be in the %s states before moving to %s state. Instead it is in %s state"
- .format(groupId, targetState.validPreviousStates.mkString(","), targetState, state))
- }
-
- def isInStates(states: collection.Set[String]): Boolean = {
- states.contains(state.toLowerCaseString)
- }
-
- override def toString: String = {
- "GroupMetadata(" +
- s"groupId=$groupId, " +
- s"generation=$generationId, " +
- s"protocolType=$protocolType, " +
- s"currentState=$currentState, " +
- s"members=$members)"
- }
-
-}
-
diff --git a/core/src/main/scala/kafka/coordinator/group/GroupMetadataManager.scala b/core/src/main/scala/kafka/coordinator/group/GroupMetadataManager.scala
deleted file mode 100644
index 3e2f707c631..00000000000
--- a/core/src/main/scala/kafka/coordinator/group/GroupMetadataManager.scala
+++ /dev/null
@@ -1,1290 +0,0 @@
-/*
- * 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 kafka.coordinator.group
-
-import java.nio.ByteBuffer
-import java.util.{Optional, OptionalInt, OptionalLong}
-import java.util.concurrent.atomic.AtomicBoolean
-import java.util.concurrent.locks.ReentrantLock
-import java.util.concurrent.{CompletableFuture, ConcurrentHashMap}
-import java.util.function.Supplier
-import com.yammer.metrics.core.Gauge
-import kafka.cluster.Partition
-import kafka.coordinator.group.GroupMetadataManager.maybeConvertOffsetCommitError
-import kafka.server.ReplicaManager
-import kafka.utils.CoreUtils.inLock
-import kafka.utils._
-import org.apache.kafka.common.compress.Compression
-import org.apache.kafka.common.errors.UnsupportedVersionException
-import org.apache.kafka.common.internals.Topic
-import org.apache.kafka.common.metrics.{Metrics, Sensor}
-import org.apache.kafka.common.metrics.stats.{Avg, Max, Meter}
-import org.apache.kafka.common.protocol.{ByteBufferAccessor, Errors, MessageUtil}
-import org.apache.kafka.common.record._
-import org.apache.kafka.common.requests.OffsetFetchResponse.PartitionData
-import org.apache.kafka.common.requests.ProduceResponse.PartitionResponse
-import org.apache.kafka.common.requests.{OffsetCommitRequest, OffsetFetchResponse}
-import org.apache.kafka.common.utils.{Time, Utils}
-import org.apache.kafka.common.{TopicIdPartition, TopicPartition}
-import org.apache.kafka.coordinator.group.{OffsetAndMetadata, OffsetConfig}
-import org.apache.kafka.coordinator.group.generated.{CoordinatorRecordType, GroupMetadataValue, LegacyOffsetCommitKey, OffsetCommitKey, OffsetCommitValue, GroupMetadataKey => GroupMetadataKeyData}
-import org.apache.kafka.server.common.RequestLocal
-import org.apache.kafka.server.metrics.KafkaMetricsGroup
-import org.apache.kafka.server.storage.log.FetchIsolation
-import org.apache.kafka.server.util.KafkaScheduler
-import org.apache.kafka.storage.internals.log.{AppendOrigin, VerificationGuard}
-
-import scala.collection._
-import scala.collection.mutable.ArrayBuffer
-import scala.jdk.CollectionConverters._
-
-class GroupMetadataManager(brokerId: Int,
- config: OffsetConfig,
- val replicaManager: ReplicaManager,
- time: Time,
- metrics: Metrics) extends Logging {
- // Visible for test.
- private[group] val metricsGroup: KafkaMetricsGroup = new KafkaMetricsGroup(this.getClass)
-
- private val compression: Compression = Compression.of(config.offsetsTopicCompressionType).build()
-
- private val groupMetadataCache = new Pool[String, GroupMetadata]
-
- /* lock protecting access to loading and owned partition sets */
- private val partitionLock = new ReentrantLock()
-
- /* partitions of consumer groups that are being loaded, its lock should be always called BEFORE the group lock if needed */
- private val loadingPartitions: mutable.Set[Int] = mutable.Set()
-
- /* partitions of consumer groups that are assigned, using the same loading partition lock */
- private val ownedPartitions: mutable.Set[Int] = mutable.Set()
-
- /* shutting down flag */
- private val shuttingDown = new AtomicBoolean(false)
-
- /* number of partitions for the consumer metadata topic */
- @volatile private var groupMetadataTopicPartitionCount: Int = _
-
- /* single-thread scheduler to handle offset/group metadata cache loading and unloading */
- private val scheduler = new KafkaScheduler(1, true, "group-metadata-manager-")
-
- /* The groups with open transactional offsets commits per producer. We need this because when the commit or abort
- * marker comes in for a transaction, it is for a particular partition on the offsets topic and a particular producerId.
- * We use this structure to quickly find the groups which need to be updated by the commit/abort marker. */
- private val openGroupsForProducer = mutable.HashMap[Long, mutable.Set[String]]()
-
- /* Track the epoch in which we (un)loaded group state to detect racing LeaderAndIsr requests */
- private [group] val epochForPartitionId = new ConcurrentHashMap[Int, java.lang.Integer]()
-
- /* setup metrics*/
- private val partitionLoadSensor = metrics.sensor(GroupMetadataManager.LoadTimeSensor)
-
- partitionLoadSensor.add(metrics.metricName("partition-load-time-max",
- GroupMetadataManager.MetricsGroup,
- "The max time it took to load the partitions in the last 30sec"), new Max())
- partitionLoadSensor.add(metrics.metricName("partition-load-time-avg",
- GroupMetadataManager.MetricsGroup,
- "The avg time it took to load the partitions in the last 30sec"), new Avg())
-
- val offsetCommitsSensor: Sensor = metrics.sensor(GroupMetadataManager.OffsetCommitsSensor)
-
- offsetCommitsSensor.add(new Meter(
- metrics.metricName("offset-commit-rate",
- "group-coordinator-metrics",
- "The rate of committed offsets"),
- metrics.metricName("offset-commit-count",
- "group-coordinator-metrics",
- "The total number of committed offsets")))
-
- val offsetExpiredSensor: Sensor = metrics.sensor(GroupMetadataManager.OffsetExpiredSensor)
-
- offsetExpiredSensor.add(new Meter(
- metrics.metricName("offset-expiration-rate",
- "group-coordinator-metrics",
- "The rate of expired offsets"),
- metrics.metricName("offset-expiration-count",
- "group-coordinator-metrics",
- "The total number of expired offsets")))
-
- this.logIdent = s"[GroupMetadataManager brokerId=$brokerId] "
-
- private def recreateGauge[T](name: String, metric: Supplier[T]): Gauge[T] = {
- metricsGroup.removeMetric(name)
- metricsGroup.newGauge(name, metric)
- }
-
- recreateGauge("NumOffsets",
- () => groupMetadataCache.values.map { group =>
- group.inLock { group.numOffsets }
- }.sum
- )
-
- recreateGauge("NumGroups",
- () => groupMetadataCache.size
- )
-
- recreateGauge("NumGroupsPreparingRebalance",
- () => groupMetadataCache.values.count { group =>
- group synchronized {
- group.is(PreparingRebalance)
- }
- })
-
- recreateGauge("NumGroupsCompletingRebalance",
- () => groupMetadataCache.values.count { group =>
- group synchronized {
- group.is(CompletingRebalance)
- }
- })
-
- recreateGauge("NumGroupsStable",
- () => groupMetadataCache.values.count { group =>
- group synchronized {
- group.is(Stable)
- }
- })
-
- recreateGauge("NumGroupsDead",
- () => groupMetadataCache.values.count { group =>
- group synchronized {
- group.is(Dead)
- }
- })
-
- recreateGauge("NumGroupsEmpty",
- () => groupMetadataCache.values.count { group =>
- group synchronized {
- group.is(Empty)
- }
- })
-
- def startup(retrieveGroupMetadataTopicPartitionCount: () => Int, enableMetadataExpiration: Boolean): Unit = {
- groupMetadataTopicPartitionCount = retrieveGroupMetadataTopicPartitionCount()
- scheduler.startup()
- if (enableMetadataExpiration) {
- scheduler.schedule("delete-expired-group-metadata",
- () => cleanupGroupMetadata(),
- 0L,
- config.offsetsRetentionCheckIntervalMs)
- }
- }
-
- def currentGroups: Iterable[GroupMetadata] = groupMetadataCache.values
-
- def isPartitionOwned(partition: Int): Boolean = inLock(partitionLock) { ownedPartitions.contains(partition) }
-
- def isPartitionLoading(partition: Int): Boolean = inLock(partitionLock) { loadingPartitions.contains(partition) }
-
- def partitionFor(groupId: String): Int = Utils.abs(groupId.hashCode) % groupMetadataTopicPartitionCount
-
- def isGroupLocal(groupId: String): Boolean = isPartitionOwned(partitionFor(groupId))
-
- def isGroupLoading(groupId: String): Boolean = isPartitionLoading(partitionFor(groupId))
-
- def isLoading: Boolean = inLock(partitionLock) { loadingPartitions.nonEmpty }
-
- // return true iff group is owned and the group doesn't exist
- def groupNotExists(groupId: String): Boolean = inLock(partitionLock) {
- isGroupLocal(groupId) && getGroup(groupId).forall { group =>
- group.inLock(group.is(Dead))
- }
- }
-
- /**
- * Get the group associated with the given groupId or null if not found
- */
- def getGroup(groupId: String): Option[GroupMetadata] = {
- Option(groupMetadataCache.get(groupId))
- }
-
- /**
- * Get the group associated with the given groupId - the group is created if createIfNotExist
- * is true - or null if not found
- */
- def getOrMaybeCreateGroup(groupId: String, createIfNotExist: Boolean): Option[GroupMetadata] = {
- if (createIfNotExist)
- Option(groupMetadataCache.getAndMaybePut(groupId, new GroupMetadata(groupId, Empty, time)))
- else
- Option(groupMetadataCache.get(groupId))
- }
-
- /**
- * Add a group or get the group associated with the given groupId if it already exists
- */
- def addGroup(group: GroupMetadata): GroupMetadata = {
- val currentGroup = groupMetadataCache.putIfNotExists(group.groupId, group)
- if (currentGroup != null) {
- currentGroup
- } else {
- group
- }
- }
-
- def storeGroup(group: GroupMetadata,
- groupAssignment: Map[String, Array[Byte]],
- responseCallback: Errors => Unit,
- requestLocal: RequestLocal = RequestLocal.noCaching): Unit = {
- if (onlinePartition(partitionFor(group.groupId)).isDefined) {
- // We always use CREATE_TIME, like the producer. The conversion to LOG_APPEND_TIME (if necessary) happens automatically.
- val timestampType = TimestampType.CREATE_TIME
- val timestamp = time.milliseconds()
- val key = GroupMetadataManager.groupMetadataKey(group.groupId)
- val value = GroupMetadataManager.groupMetadataValue(group, groupAssignment)
-
- val records = {
- val buffer = ByteBuffer.allocate(AbstractRecords.estimateSizeInBytes(RecordBatch.CURRENT_MAGIC_VALUE, compression.`type`(),
- Seq(new SimpleRecord(timestamp, key, value)).asJava))
- val builder = MemoryRecords.builder(buffer, RecordBatch.CURRENT_MAGIC_VALUE, compression, timestampType, 0L)
- builder.append(timestamp, key, value)
- builder.build()
- }
-
- val groupMetadataPartition = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, partitionFor(group.groupId))
- val groupMetadataRecords = Map(groupMetadataPartition -> records)
- val generationId = group.generationId
-
- // set the callback function to insert the created group into cache after log append completed
- def putCacheCallback(responseStatus: Map[TopicPartition, PartitionResponse]): Unit = {
- // the append response should only contain the topics partition
- if (responseStatus.size != 1 || !responseStatus.contains(groupMetadataPartition))
- throw new IllegalStateException("Append status %s should only have one partition %s"
- .format(responseStatus, groupMetadataPartition))
-
- // construct the error status in the propagated assignment response in the cache
- val status = responseStatus(groupMetadataPartition)
-
- val responseError = if (status.error == Errors.NONE) {
- Errors.NONE
- } else {
- debug(s"Metadata from group ${group.groupId} with generation $generationId failed when appending to log " +
- s"due to ${status.error.exceptionName}")
-
- // transform the log append error code to the corresponding the commit status error code
- status.error match {
- case Errors.UNKNOWN_TOPIC_OR_PARTITION
- | Errors.NOT_ENOUGH_REPLICAS
- | Errors.NOT_ENOUGH_REPLICAS_AFTER_APPEND =>
- Errors.COORDINATOR_NOT_AVAILABLE
-
- case Errors.NOT_LEADER_OR_FOLLOWER
- | Errors.KAFKA_STORAGE_ERROR =>
- Errors.NOT_COORDINATOR
-
- case Errors.REQUEST_TIMED_OUT =>
- Errors.REBALANCE_IN_PROGRESS
-
- case Errors.MESSAGE_TOO_LARGE
- | Errors.RECORD_LIST_TOO_LARGE
- | Errors.INVALID_FETCH_SIZE =>
-
- error(s"Appending metadata message for group ${group.groupId} generation $generationId failed due to " +
- s"${status.error.exceptionName}, returning UNKNOWN error code to the client")
-
- Errors.UNKNOWN_SERVER_ERROR
-
- case other =>
- error(s"Appending metadata message for group ${group.groupId} generation $generationId failed " +
- s"due to unexpected error: ${status.error.exceptionName}")
-
- other
- }
- }
-
- responseCallback(responseError)
- }
-
- appendForGroup(group, groupMetadataRecords, requestLocal, putCacheCallback)
- } else {
- responseCallback(Errors.NOT_COORDINATOR)
- }
- }
-
- // This method should be called under the group lock to ensure atomicity of the update to the the in-memory and persisted state.
- private def appendForGroup(
- group: GroupMetadata,
- records: Map[TopicPartition, MemoryRecords],
- requestLocal: RequestLocal,
- callback: Map[TopicPartition, PartitionResponse] => Unit,
- verificationGuards: Map[TopicPartition, VerificationGuard] = Map.empty
- ): Unit = {
- // call replica manager to append the group message
- replicaManager.appendRecords(
- timeout = config.offsetCommitTimeoutMs.toLong,
- requiredAcks = -1,
- internalTopicsAllowed = true,
- origin = AppendOrigin.COORDINATOR,
- entriesPerPartition = records,
- delayedProduceLock = Some(group.lock),
- responseCallback = callback,
- requestLocal = requestLocal,
- verificationGuards = verificationGuards
- )
- }
-
- private def generateOffsetRecords(magicValue: Byte,
- isTxnOffsetCommit: Boolean,
- groupId: String,
- offsetTopicPartition: TopicPartition,
- filteredOffsetMetadata: Map[TopicIdPartition, OffsetAndMetadata],
- producerId: Long,
- producerEpoch: Short): Map[TopicPartition, MemoryRecords] = {
- // We always use CREATE_TIME, like the producer. The conversion to LOG_APPEND_TIME (if necessary) happens automatically.
- val timestampType = TimestampType.CREATE_TIME
- val timestamp = time.milliseconds()
-
- val records = filteredOffsetMetadata.map { case (topicIdPartition, offsetAndMetadata) =>
- val key = GroupMetadataManager.offsetCommitKey(groupId, topicIdPartition.topicPartition)
- val value = GroupMetadataManager.offsetCommitValue(offsetAndMetadata)
- new SimpleRecord(timestamp, key, value)
- }
- val buffer = ByteBuffer.allocate(AbstractRecords.estimateSizeInBytes(magicValue, compression.`type`(), records.asJava))
-
- if (isTxnOffsetCommit && magicValue < RecordBatch.MAGIC_VALUE_V2)
- throw Errors.UNSUPPORTED_FOR_MESSAGE_FORMAT.exception("Attempting to make a transaction offset commit with an invalid magic: " + magicValue)
-
- val builder = MemoryRecords.builder(buffer, magicValue, compression, timestampType, 0L, time.milliseconds(),
- producerId, producerEpoch, 0, isTxnOffsetCommit, RecordBatch.NO_PARTITION_LEADER_EPOCH)
-
- records.foreach(builder.append)
- Map(offsetTopicPartition -> builder.build())
- }
-
- private def createPutCacheCallback(isTxnOffsetCommit: Boolean,
- group: GroupMetadata,
- consumerId: String,
- offsetMetadata: immutable.Map[TopicIdPartition, OffsetAndMetadata],
- filteredOffsetMetadata: Map[TopicIdPartition, OffsetAndMetadata],
- responseCallback: immutable.Map[TopicIdPartition, Errors] => Unit,
- producerId: Long,
- records: Map[TopicPartition, MemoryRecords]): Map[TopicPartition, PartitionResponse] => Unit = {
- val offsetTopicPartition = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, partitionFor(group.groupId))
- // set the callback function to insert offsets into cache after log append completed
- def putCacheCallback(responseStatus: Map[TopicPartition, PartitionResponse]): Unit = {
- // the append response should only contain the topics partition
- if (responseStatus.size != 1 || !responseStatus.contains(offsetTopicPartition))
- throw new IllegalStateException("Append status %s should only have one partition %s"
- .format(responseStatus, offsetTopicPartition))
-
- // construct the commit response status and insert
- // the offset and metadata to cache if the append status has no error
- val status = responseStatus(offsetTopicPartition)
-
- val responseError = group.inLock {
- if (status.error == Errors.NONE) {
- if (!group.is(Dead)) {
- filteredOffsetMetadata.foreachEntry { (topicIdPartition, offsetAndMetadata) =>
- if (isTxnOffsetCommit)
- group.onTxnOffsetCommitAppend(producerId, topicIdPartition, CommitRecordMetadataAndOffset(Some(status.baseOffset), offsetAndMetadata))
- else
- group.onOffsetCommitAppend(topicIdPartition, CommitRecordMetadataAndOffset(Some(status.baseOffset), offsetAndMetadata))
- }
- }
-
- // Record the number of offsets committed to the log
- offsetCommitsSensor.record(records.size)
-
- Errors.NONE
- } else {
- if (!group.is(Dead)) {
- if (!group.hasPendingOffsetCommitsFromProducer(producerId))
- removeProducerGroup(producerId, group.groupId)
- filteredOffsetMetadata.foreachEntry { (topicIdPartition, offsetAndMetadata) =>
- if (isTxnOffsetCommit)
- group.failPendingTxnOffsetCommit(producerId, topicIdPartition)
- else
- group.failPendingOffsetWrite(topicIdPartition, offsetAndMetadata)
- }
- }
-
- debug(s"Offset commit $filteredOffsetMetadata from group ${group.groupId}, consumer $consumerId " +
- s"with generation ${group.generationId} failed when appending to log due to ${status.error.exceptionName}")
-
- maybeConvertOffsetCommitError(status.error)
- }
- }
-
- // compute the final error codes for the commit response
- val commitStatus = offsetMetadata.map { case (topicIdPartition, offsetAndMetadata) =>
- if (!validateOffsetMetadataLength(offsetAndMetadata.metadata))
- (topicIdPartition, Errors.OFFSET_METADATA_TOO_LARGE)
- else
- (topicIdPartition, responseError)
- }
-
- // finally trigger the callback logic passed from the API layer
- responseCallback(commitStatus)
- }
- putCacheCallback
- }
-
- /**
- * Store offsets by appending it to the replicated log and then inserting to cache
- *
- * This method should be called under the group lock to ensure validations and updates are all performed
- * atomically.
- */
- def storeOffsets(group: GroupMetadata,
- consumerId: String,
- offsetTopicPartition: TopicPartition,
- offsetMetadata: immutable.Map[TopicIdPartition, OffsetAndMetadata],
- responseCallback: immutable.Map[TopicIdPartition, Errors] => Unit,
- producerId: Long = RecordBatch.NO_PRODUCER_ID,
- producerEpoch: Short = RecordBatch.NO_PRODUCER_EPOCH,
- requestLocal: RequestLocal = RequestLocal.noCaching,
- verificationGuard: Option[VerificationGuard]): Unit = {
- if (!group.hasReceivedConsistentOffsetCommits)
- warn(s"group: ${group.groupId} with leader: ${group.leaderOrNull} has received offset commits from consumers as well " +
- s"as transactional producers. Mixing both types of offset commits will generally result in surprises and " +
- s"should be avoided.")
-
- val filteredOffsetMetadata = offsetMetadata.filter { case (_, offsetAndMetadata) =>
- validateOffsetMetadataLength(offsetAndMetadata.metadata)
- }
- if (filteredOffsetMetadata.isEmpty) {
- // compute the final error codes for the commit response
- val commitStatus = offsetMetadata.map { case (k, _) => k -> Errors.OFFSET_METADATA_TOO_LARGE }
- responseCallback(commitStatus)
- return
- }
-
- if (onlinePartition(partitionFor(group.groupId)).isEmpty) {
- val commitStatus = offsetMetadata.map { case (topicIdPartition, _) =>
- (topicIdPartition, Errors.NOT_COORDINATOR)
- }
- responseCallback(commitStatus)
- return
- }
-
- val isTxnOffsetCommit = producerId != RecordBatch.NO_PRODUCER_ID
- val records = generateOffsetRecords(RecordBatch.CURRENT_MAGIC_VALUE, isTxnOffsetCommit, group.groupId, offsetTopicPartition, filteredOffsetMetadata, producerId, producerEpoch)
- val putCacheCallback = createPutCacheCallback(isTxnOffsetCommit, group, consumerId, offsetMetadata, filteredOffsetMetadata, responseCallback, producerId, records)
-
- val verificationGuards = verificationGuard.map(guard => offsetTopicPartition -> guard).toMap
-
- if (isTxnOffsetCommit) {
- addProducerGroup(producerId, group.groupId)
- group.prepareTxnOffsetCommit(producerId, filteredOffsetMetadata)
- } else {
- group.prepareOffsetCommit(filteredOffsetMetadata)
- }
-
- appendForGroup(group, records, requestLocal, putCacheCallback, verificationGuards)
- }
-
- /**
- * The most important guarantee that this API provides is that it should never return a stale offset. i.e., it either
- * returns the current offset or it begins to sync the cache from the log (and returns an error code).
- */
- def getOffsets(groupId: String, requireStable: Boolean, topicPartitionsOpt: Option[Seq[TopicPartition]]): Map[TopicPartition, PartitionData] = {
- trace("Getting offsets of %s for group %s.".format(topicPartitionsOpt.getOrElse("all partitions"), groupId))
- val group = groupMetadataCache.get(groupId)
- if (group == null) {
- topicPartitionsOpt.getOrElse(Seq.empty[TopicPartition]).map { topicPartition =>
- val partitionData = new PartitionData(OffsetFetchResponse.INVALID_OFFSET,
- Optional.empty(), "", Errors.NONE)
- topicPartition -> partitionData
- }.toMap
- } else {
- group.inLock {
- if (group.is(Dead)) {
- topicPartitionsOpt.getOrElse(Seq.empty[TopicPartition]).map { topicPartition =>
- val partitionData = new PartitionData(OffsetFetchResponse.INVALID_OFFSET,
- Optional.empty(), "", Errors.NONE)
- topicPartition -> partitionData
- }.toMap
- } else {
- val topicPartitions = topicPartitionsOpt.getOrElse(group.allOffsets.keySet)
-
- topicPartitions.map { topicPartition =>
- if (requireStable && group.hasPendingOffsetCommitsForTopicPartition(topicPartition)) {
- topicPartition -> new PartitionData(OffsetFetchResponse.INVALID_OFFSET,
- Optional.empty(), "", Errors.UNSTABLE_OFFSET_COMMIT)
- } else {
- val partitionData = group.offset(topicPartition) match {
- case None =>
- new PartitionData(OffsetFetchResponse.INVALID_OFFSET,
- Optional.empty(), "", Errors.NONE)
- case Some(offsetAndMetadata) =>
- val leaderEpoch: Optional[Integer] = if (offsetAndMetadata.leaderEpoch.isPresent) {
- Optional.of(offsetAndMetadata.leaderEpoch.getAsInt)
- } else {
- Optional.empty()
- }
- new PartitionData(offsetAndMetadata.committedOffset, leaderEpoch, offsetAndMetadata.metadata, Errors.NONE)
- }
- topicPartition -> partitionData
- }
- }.toMap
- }
- }
- }
- }
-
- /**
- * Asynchronously read the partition from the offsets topic and populate the cache
- */
- def scheduleLoadGroupAndOffsets(offsetsPartition: Int, coordinatorEpoch: Int, onGroupLoaded: GroupMetadata => Unit): Unit = {
- val topicPartition = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, offsetsPartition)
- info(s"Scheduling loading of offsets and group metadata from $topicPartition for epoch $coordinatorEpoch")
- val startTimeMs = time.milliseconds()
- scheduler.scheduleOnce(topicPartition.toString, () => loadGroupsAndOffsets(topicPartition, coordinatorEpoch, onGroupLoaded, startTimeMs))
- }
-
- private[group] def loadGroupsAndOffsets(
- topicPartition: TopicPartition,
- coordinatorEpoch: Int,
- onGroupLoaded: GroupMetadata => Unit,
- startTimeMs: java.lang.Long
- ): Unit = {
- if (!maybeUpdateCoordinatorEpoch(topicPartition.partition, OptionalInt.of(coordinatorEpoch))) {
- info(s"Not loading offsets and group metadata for $topicPartition " +
- s"in epoch $coordinatorEpoch since current epoch is ${epochForPartitionId.get(topicPartition.partition)}")
- } else if (!addLoadingPartition(topicPartition.partition)) {
- info(s"Already loading offsets and group metadata from $topicPartition")
- } else {
- try {
- val schedulerTimeMs = time.milliseconds() - startTimeMs
- debug(s"Started loading offsets and group metadata from $topicPartition for epoch $coordinatorEpoch")
- doLoadGroupsAndOffsets(topicPartition, onGroupLoaded)
- val endTimeMs = time.milliseconds()
- val totalLoadingTimeMs = endTimeMs - startTimeMs
- partitionLoadSensor.record(totalLoadingTimeMs.toDouble, endTimeMs, false)
- info(s"Finished loading offsets and group metadata from $topicPartition "
- + s"in $totalLoadingTimeMs milliseconds for epoch $coordinatorEpoch, of which " +
- s"$schedulerTimeMs milliseconds was spent in the scheduler.")
- } catch {
- case t: Throwable => error(s"Error loading offsets from $topicPartition", t)
- } finally {
- inLock(partitionLock) {
- ownedPartitions.add(topicPartition.partition)
- loadingPartitions.remove(topicPartition.partition)
- }
- }
- }
- }
-
- private def doLoadGroupsAndOffsets(topicPartition: TopicPartition, onGroupLoaded: GroupMetadata => Unit): Unit = {
- def logEndOffset: Long = replicaManager.getLogEndOffset(topicPartition).getOrElse(-1L)
-
- replicaManager.getLog(topicPartition) match {
- case None =>
- warn(s"Attempted to load offsets and group metadata from $topicPartition, but found no log")
-
- case Some(log) =>
- val loadedOffsets = mutable.Map[GroupTopicPartition, CommitRecordMetadataAndOffset]()
- val pendingOffsets = mutable.Map[Long, mutable.Map[GroupTopicPartition, CommitRecordMetadataAndOffset]]()
- val loadedGroups = mutable.Map[String, GroupMetadata]()
- val removedGroups = mutable.Set[String]()
-
- // buffer may not be needed if records are read from memory
- var buffer = ByteBuffer.allocate(0)
-
- // loop breaks if leader changes at any time during the load, since logEndOffset is -1
- var currOffset = log.logStartOffset
-
- // loop breaks if no records have been read, since the end of the log has been reached
- var readAtLeastOneRecord = true
-
- while (currOffset < logEndOffset && readAtLeastOneRecord && !shuttingDown.get()) {
- val fetchDataInfo = log.read(currOffset, config.loadBufferSize, FetchIsolation.LOG_END, true)
-
- readAtLeastOneRecord = fetchDataInfo.records.sizeInBytes > 0
-
- val memRecords = (fetchDataInfo.records: @unchecked) match {
- case records: MemoryRecords => records
- case fileRecords: FileRecords =>
- val sizeInBytes = fileRecords.sizeInBytes
- val bytesNeeded = Math.max(config.loadBufferSize, sizeInBytes)
-
- // minOneMessage = true in the above log.read means that the buffer may need to be grown to ensure progress can be made
- if (buffer.capacity < bytesNeeded) {
- if (config.loadBufferSize < bytesNeeded)
- warn(s"Loaded offsets and group metadata from $topicPartition with buffer larger ($bytesNeeded bytes) than " +
- s"configured offsets.load.buffer.size (${config.loadBufferSize} bytes)")
-
- buffer = ByteBuffer.allocate(bytesNeeded)
- } else {
- buffer.clear()
- }
-
- fileRecords.readInto(buffer, 0)
- MemoryRecords.readableRecords(buffer)
- }
-
- memRecords.batches.forEach { batch =>
- val isTxnOffsetCommit = batch.isTransactional
- if (batch.isControlBatch) {
- val recordIterator = batch.iterator
- if (recordIterator.hasNext) {
- val record = recordIterator.next()
- val controlRecord = ControlRecordType.parse(record.key)
- if (controlRecord == ControlRecordType.COMMIT) {
- pendingOffsets.getOrElse(batch.producerId, mutable.Map[GroupTopicPartition, CommitRecordMetadataAndOffset]())
- .foreach {
- case (groupTopicPartition, commitRecordMetadataAndOffset) =>
- if (!loadedOffsets.contains(groupTopicPartition) || loadedOffsets(groupTopicPartition).olderThan(commitRecordMetadataAndOffset))
- loadedOffsets.put(groupTopicPartition, commitRecordMetadataAndOffset)
- }
- }
- pendingOffsets.remove(batch.producerId)
- }
- } else {
- var batchBaseOffset: Option[Long] = None
- for (record <- batch.asScala) {
- require(record.hasKey, "Group metadata/offset entry key should not be null")
- if (batchBaseOffset.isEmpty)
- batchBaseOffset = Some(record.offset)
- GroupMetadataManager.readMessageKey(record.key) match {
- case offsetKey: OffsetKey =>
- if (isTxnOffsetCommit && !pendingOffsets.contains(batch.producerId))
- pendingOffsets.put(batch.producerId, mutable.Map[GroupTopicPartition, CommitRecordMetadataAndOffset]())
-
- // load offset
- val groupTopicPartition = offsetKey.key
- if (!record.hasValue) {
- if (isTxnOffsetCommit)
- pendingOffsets(batch.producerId).remove(groupTopicPartition)
- else
- loadedOffsets.remove(groupTopicPartition)
- } else {
- val offsetAndMetadata = GroupMetadataManager.readOffsetMessageValue(record.value)
- if (isTxnOffsetCommit)
- pendingOffsets(batch.producerId).put(groupTopicPartition, CommitRecordMetadataAndOffset(batchBaseOffset, offsetAndMetadata))
- else
- loadedOffsets.put(groupTopicPartition, CommitRecordMetadataAndOffset(batchBaseOffset, offsetAndMetadata))
- }
-
- case groupMetadataKey: GroupMetadataKey =>
- // load group metadata
- val groupId = groupMetadataKey.key
- val groupMetadata = GroupMetadataManager.readGroupMessageValue(groupId, record.value, time)
- if (groupMetadata != null) {
- removedGroups.remove(groupId)
- loadedGroups.put(groupId, groupMetadata)
- } else {
- loadedGroups.remove(groupId)
- removedGroups.add(groupId)
- }
-
- case unknownKey: UnknownKey =>
- warn(s"Unknown message key with version ${unknownKey.version}" +
- s" while loading offsets and group metadata from $topicPartition. Ignoring it. " +
- "It could be a left over from an aborted upgrade.")
- }
- }
- }
- currOffset = batch.nextOffset
- }
- }
-
- val (groupOffsets, emptyGroupOffsets) = loadedOffsets
- .groupBy(_._1.group)
- .map { case (k, v) =>
- k -> v.map { case (groupTopicPartition, offset) => (groupTopicPartition.topicPartition, offset) }
- }.partition { case (group, _) => loadedGroups.contains(group) }
-
- val pendingOffsetsByGroup = mutable.Map[String, mutable.Map[Long, mutable.Map[TopicPartition, CommitRecordMetadataAndOffset]]]()
- pendingOffsets.foreachEntry { (producerId, producerOffsets) =>
- producerOffsets.keySet.map(_.group).foreach(addProducerGroup(producerId, _))
- producerOffsets
- .groupBy(_._1.group)
- .foreachEntry { (group, offsets) =>
- val groupPendingOffsets = pendingOffsetsByGroup.getOrElseUpdate(group, mutable.Map.empty[Long, mutable.Map[TopicPartition, CommitRecordMetadataAndOffset]])
- val groupProducerOffsets = groupPendingOffsets.getOrElseUpdate(producerId, mutable.Map.empty[TopicPartition, CommitRecordMetadataAndOffset])
- groupProducerOffsets ++= offsets.map { case (groupTopicPartition, offset) =>
- (groupTopicPartition.topicPartition, offset)
- }
- }
- }
-
- val (pendingGroupOffsets, pendingEmptyGroupOffsets) = pendingOffsetsByGroup
- .partition { case (group, _) => loadedGroups.contains(group)}
-
- loadedGroups.values.foreach { group =>
- val offsets = groupOffsets.getOrElse(group.groupId, Map.empty[TopicPartition, CommitRecordMetadataAndOffset])
- val pendingOffsets = pendingGroupOffsets.getOrElse(group.groupId, Map.empty[Long, mutable.Map[TopicPartition, CommitRecordMetadataAndOffset]])
- debug(s"Loaded group metadata $group with offsets $offsets and pending offsets $pendingOffsets")
- loadGroup(group, offsets, pendingOffsets)
- onGroupLoaded(group)
- }
-
- // load groups which store offsets in kafka, but which have no active members and thus no group
- // metadata stored in the log
- (emptyGroupOffsets.keySet ++ pendingEmptyGroupOffsets.keySet).foreach { groupId =>
- val group = new GroupMetadata(groupId, Empty, time)
- val offsets = emptyGroupOffsets.getOrElse(groupId, Map.empty[TopicPartition, CommitRecordMetadataAndOffset])
- val pendingOffsets = pendingEmptyGroupOffsets.getOrElse(groupId, Map.empty[Long, mutable.Map[TopicPartition, CommitRecordMetadataAndOffset]])
- debug(s"Loaded group metadata $group with offsets $offsets and pending offsets $pendingOffsets")
- loadGroup(group, offsets, pendingOffsets)
- onGroupLoaded(group)
- }
-
- removedGroups.foreach { groupId =>
- // if the cache already contains a group which should be removed, raise an error. Note that it
- // is possible (however unlikely) for a consumer group to be removed, and then to be used only for
- // offset storage (i.e. by "simple" consumers)
- if (groupMetadataCache.contains(groupId) && !emptyGroupOffsets.contains(groupId))
- throw new IllegalStateException(s"Unexpected unload of active group $groupId while " +
- s"loading partition $topicPartition")
- }
- }
- }
-
- private def loadGroup(group: GroupMetadata, offsets: Map[TopicPartition, CommitRecordMetadataAndOffset],
- pendingTransactionalOffsets: Map[Long, mutable.Map[TopicPartition, CommitRecordMetadataAndOffset]]): Unit = {
- // offsets are initialized prior to loading the group into the cache to ensure that clients see a consistent
- // view of the group's offsets
- trace(s"Initialized offsets $offsets for group ${group.groupId}")
- group.initializeOffsets(offsets, pendingTransactionalOffsets.toMap)
-
- val currentGroup = addGroup(group)
- if (group != currentGroup)
- debug(s"Attempt to load group ${group.groupId} from log with generation ${group.generationId} failed " +
- s"because there is already a cached group with generation ${currentGroup.generationId}")
- }
-
- /**
- * When this broker becomes a follower for an offsets topic partition clear out the cache for groups that belong to
- * that partition.
- *
- * @param offsetsPartition Groups belonging to this partition of the offsets topic will be deleted from the cache.
- */
- def removeGroupsForPartition(offsetsPartition: Int,
- coordinatorEpoch: OptionalInt,
- onGroupUnloaded: GroupMetadata => Unit): Unit = {
- val topicPartition = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, offsetsPartition)
- info(s"Scheduling unloading of offsets and group metadata from $topicPartition")
- scheduler.scheduleOnce(topicPartition.toString, () => removeGroupsAndOffsets(topicPartition, coordinatorEpoch, onGroupUnloaded))
- }
-
- private [group] def removeGroupsAndOffsets(topicPartition: TopicPartition,
- coordinatorEpoch: OptionalInt,
- onGroupUnloaded: GroupMetadata => Unit): Unit = {
- val offsetsPartition = topicPartition.partition
- if (maybeUpdateCoordinatorEpoch(offsetsPartition, coordinatorEpoch)) {
- var numOffsetsRemoved = 0
- var numGroupsRemoved = 0
-
- debug(s"Started unloading offsets and group metadata for $topicPartition for " +
- s"coordinator epoch $coordinatorEpoch")
- inLock(partitionLock) {
- // we need to guard the group removal in cache in the loading partition lock
- // to prevent coordinator's check-and-get-group race condition
- ownedPartitions.remove(offsetsPartition)
- loadingPartitions.remove(offsetsPartition)
-
- for (group <- groupMetadataCache.values) {
- if (partitionFor(group.groupId) == offsetsPartition) {
- onGroupUnloaded(group)
- groupMetadataCache.remove(group.groupId, group)
- removeGroupFromAllProducers(group.groupId)
- numGroupsRemoved += 1
- numOffsetsRemoved += group.numOffsets
- }
- }
- }
- info(s"Finished unloading $topicPartition for coordinator epoch $coordinatorEpoch. " +
- s"Removed $numOffsetsRemoved cached offsets and $numGroupsRemoved cached groups.")
- } else {
- info(s"Not removing offsets and group metadata for $topicPartition " +
- s"in epoch $coordinatorEpoch since current epoch is ${epochForPartitionId.get(topicPartition.partition)}")
- }
- }
-
- /**
- * Update the cached coordinator epoch if the new value is larger than the old value.
- * @return true if `epochOpt` is either empty or contains a value greater than or equal to the current epoch
- */
- private def maybeUpdateCoordinatorEpoch(
- partitionId: Int,
- epochOpt: OptionalInt
- ): Boolean = {
- val updatedEpoch = epochForPartitionId.compute(partitionId, (_, currentEpoch) => {
- if (currentEpoch == null) {
- if (epochOpt.isPresent) epochOpt.getAsInt
- else null
- } else {
- if (epochOpt.isPresent && epochOpt.getAsInt > currentEpoch) epochOpt.getAsInt
- else currentEpoch
- }
- })
- if (epochOpt.isPresent) {
- epochOpt.getAsInt == updatedEpoch
- } else {
- true
- }
- }
-
- // visible for testing
- private[group] def cleanupGroupMetadata(): Unit = {
- val currentTimestamp = time.milliseconds()
- val numOffsetsRemoved = cleanupGroupMetadata(groupMetadataCache.values, RequestLocal.noCaching,
- _.removeExpiredOffsets(currentTimestamp, config.offsetsRetentionMs))
- offsetExpiredSensor.record(numOffsetsRemoved)
- if (numOffsetsRemoved > 0)
- info(s"Removed $numOffsetsRemoved expired offsets in ${time.milliseconds() - currentTimestamp} milliseconds.")
- }
-
- /**
- * This function is used to clean up group offsets given the groups and also a function that performs the offset deletion.
- * @param groups Groups whose metadata are to be cleaned up
- * @param selector A function that implements deletion of (all or part of) group offsets. This function is called while
- * a group lock is held, therefore there is no need for the caller to also obtain a group lock.
- * @return The cumulative number of offsets removed
- */
- def cleanupGroupMetadata(groups: Iterable[GroupMetadata], requestLocal: RequestLocal,
- selector: GroupMetadata => Map[TopicPartition, OffsetAndMetadata]): Int = {
- var offsetsRemoved = 0
-
- groups.foreach { group =>
- val groupId = group.groupId
- val (removedOffsets, groupIsDead, generation) = group.inLock {
- val removedOffsets = selector(group)
- if (group.is(Empty) && !group.hasOffsets) {
- info(s"Group $groupId transitioned to Dead in generation ${group.generationId}")
- group.transitionTo(Dead)
- }
- (removedOffsets, group.is(Dead), group.generationId)
- }
-
- val offsetsPartition = partitionFor(groupId)
- val appendPartition = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, offsetsPartition)
- onlinePartition(offsetsPartition) match {
- case Some(partition) =>
- // We always use CREATE_TIME, like the producer. The conversion to LOG_APPEND_TIME (if necessary) happens automatically.
- val timestampType = TimestampType.CREATE_TIME
- val timestamp = time.milliseconds()
-
- val tombstones = ArrayBuffer.empty[SimpleRecord]
- removedOffsets.foreachEntry { (topicPartition, offsetAndMetadata) =>
- trace(s"Removing expired/deleted offset and metadata for $groupId, $topicPartition: $offsetAndMetadata")
- val commitKey = GroupMetadataManager.offsetCommitKey(groupId, topicPartition)
- tombstones += new SimpleRecord(timestamp, commitKey, null)
- }
- trace(s"Marked ${removedOffsets.size} offsets in $appendPartition for deletion.")
-
- // We avoid writing the tombstone when the generationId is 0, since this group is only using
- // Kafka for offset storage.
- if (groupIsDead && groupMetadataCache.remove(groupId, group) && generation > 0) {
- // Append the tombstone messages to the partition. It is okay if the replicas don't receive these (say,
- // if we crash or leaders move) since the new leaders will still expire the consumers with heartbeat and
- // retry removing this group.
- val groupMetadataKey = GroupMetadataManager.groupMetadataKey(group.groupId)
- tombstones += new SimpleRecord(timestamp, groupMetadataKey, null)
- trace(s"Group $groupId removed from the metadata cache and marked for deletion in $appendPartition.")
- }
-
- if (tombstones.nonEmpty) {
- try {
- // do not need to require acks since even if the tombstone is lost,
- // it will be appended again in the next purge cycle
- val records = MemoryRecords.withRecords(RecordBatch.CURRENT_MAGIC_VALUE, 0L, compression, timestampType, tombstones.toArray: _*)
- partition.appendRecordsToLeader(records, origin = AppendOrigin.COORDINATOR, requiredAcks = 0,
- requestLocal = requestLocal)
-
- offsetsRemoved += removedOffsets.size
- trace(s"Successfully appended ${tombstones.size} tombstones to $appendPartition for expired/deleted " +
- s"offsets and/or metadata for group $groupId")
- } catch {
- case t: Throwable =>
- error(s"Failed to append ${tombstones.size} tombstones to $appendPartition for expired/deleted " +
- s"offsets and/or metadata for group $groupId.", t)
- // ignore and continue
- }
- }
-
-
- case None =>
- info(s"BrokerId $brokerId is no longer a coordinator for the group $groupId. Proceeding cleanup for other alive groups")
- }
- }
-
- offsetsRemoved
- }
-
- /**
- * Complete pending transactional offset commits of the groups of `producerId` from the provided
- * `completedPartitions`. This method is invoked when a commit or abort marker is fully written
- * to the log. It may be invoked when a group lock is held by the caller, for instance when delayed
- * operations are completed while appending offsets for a group. Since we need to acquire one or
- * more group metadata locks to handle transaction completion, this operation is scheduled on
- * the scheduler thread to avoid deadlocks.
- */
- def scheduleHandleTxnCompletion(producerId: Long, completedPartitions: Set[Int], isCommit: Boolean): CompletableFuture[Void] = {
- val future = new CompletableFuture[Void]()
- scheduler.scheduleOnce(s"handleTxnCompletion-$producerId", () => {
- try {
- handleTxnCompletion(producerId, completedPartitions, isCommit)
- future.complete(null)
- } catch {
- case e: Throwable => future.completeExceptionally(e)
- }
- })
- future
- }
-
- private[group] def handleTxnCompletion(producerId: Long, completedPartitions: Set[Int], isCommit: Boolean): Unit = {
- val pendingGroups = groupsBelongingToPartitions(producerId, completedPartitions)
- pendingGroups.foreach { groupId =>
- getGroup(groupId) match {
- case Some(group) => group.inLock {
- if (!group.is(Dead)) {
- group.completePendingTxnOffsetCommit(producerId, isCommit)
- removeProducerGroup(producerId, groupId)
- }
- }
- case _ =>
- info(s"Group $groupId has moved away from $brokerId after transaction marker was written but before the " +
- s"cache was updated. The cache on the new group owner will be updated instead.")
- }
- }
- }
-
- private def addProducerGroup(producerId: Long, groupId: String) = openGroupsForProducer synchronized {
- openGroupsForProducer.getOrElseUpdate(producerId, mutable.Set.empty[String]).add(groupId)
- }
-
- private def removeProducerGroup(producerId: Long, groupId: String) = openGroupsForProducer synchronized {
- openGroupsForProducer.getOrElseUpdate(producerId, mutable.Set.empty[String]).remove(groupId)
- if (openGroupsForProducer(producerId).isEmpty)
- openGroupsForProducer.remove(producerId)
- }
-
- private def groupsBelongingToPartitions(producerId: Long, partitions: Set[Int]) = openGroupsForProducer synchronized {
- val (ownedGroups, _) = openGroupsForProducer.getOrElse(producerId, mutable.Set.empty[String])
- .partition(group => partitions.contains(partitionFor(group)))
- ownedGroups
- }
-
- private def removeGroupFromAllProducers(groupId: String): Unit = openGroupsForProducer synchronized {
- openGroupsForProducer.foreachEntry { (_, groups) =>
- groups.remove(groupId)
- }
- }
-
- /*
- * Check if the offset metadata length is valid
- */
- private def validateOffsetMetadataLength(metadata: String) : Boolean = {
- metadata == null || metadata.length() <= config.maxMetadataSize
- }
-
-
- def shutdown(): Unit = {
- shuttingDown.set(true)
- scheduler.shutdown()
- metrics.removeSensor(GroupMetadataManager.LoadTimeSensor)
- metrics.removeSensor(GroupMetadataManager.OffsetCommitsSensor)
- metrics.removeSensor(GroupMetadataManager.OffsetExpiredSensor)
-
- // TODO: clear the caches
- }
-
- private def onlinePartition(partition: Int): Option[Partition] =
- replicaManager.onlinePartition(new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, partition))
-
- /**
- * Add a partition to the owned partition set.
- *
- * NOTE: this is for test only.
- */
- private[group] def addOwnedPartition(partition: Int): Unit = {
- inLock(partitionLock) {
- ownedPartitions.add(partition)
- }
- }
-
- /**
- * Add a partition to the loading partitions set. Return true if the partition was not
- * already loading.
- *
- * Visible for testing
- */
- private[group] def addLoadingPartition(partition: Int): Boolean = {
- inLock(partitionLock) {
- if (ownedPartitions.contains(partition)) {
- false
- } else {
- loadingPartitions.add(partition)
- }
- }
- }
-
-}
-
-/**
- * Messages stored for the group topic has versions for both the key and value fields. Key
- * version is used to indicate the type of the message (also to differentiate different types
- * of messages from being compacted together if they have the same field values); and value
- * version is used to evolve the messages within their data types:
- *
- * key version 0: group consumption offset
- * -> value version 0: [offset, metadata, timestamp]
- *
- * key version 1: group consumption offset
- * -> value version 1: [offset, metadata, commit_timestamp, expire_timestamp]
- *
- * key version 2: group metadata
- * -> value version 0: [protocol_type, generation, protocol, leader, members]
- */
-object GroupMetadataManager {
- // Metrics names
- val MetricsGroup: String = "group-coordinator-metrics"
- val LoadTimeSensor: String = "GroupPartitionLoadTime"
- val OffsetCommitsSensor: String = "OffsetCommits"
- val OffsetExpiredSensor: String = "OffsetExpired"
-
- /**
- * Generates the key for offset commit message for given (group, topic, partition)
- *
- * @param groupId the ID of the group to generate the key
- * @param topicPartition the TopicPartition to generate the key
- * @return key for offset commit message
- */
- def offsetCommitKey(groupId: String, topicPartition: TopicPartition): Array[Byte] = {
- MessageUtil.toCoordinatorTypePrefixedBytes(new OffsetCommitKey()
- .setGroup(groupId)
- .setTopic(topicPartition.topic)
- .setPartition(topicPartition.partition))
- }
-
- /**
- * Generates the key for group metadata message for given group
- *
- * @param groupId the ID of the group to generate the key
- * @return key bytes for group metadata message
- */
- def groupMetadataKey(groupId: String): Array[Byte] = {
- MessageUtil.toCoordinatorTypePrefixedBytes(new GroupMetadataKeyData()
- .setGroup(groupId))
- }
-
- /**
- * Generates the payload for offset commit message from given offset and metadata
- *
- * @param offsetAndMetadata consumer's current offset and metadata
- * @param maxVersion the highest version allowed, we may use a lower version for compatibility reasons
- * we serialize with the highest supported non-flexible version until a tagged field is introduced
- * or the version is bumped.
- * @return payload for offset commit message
- */
- def offsetCommitValue(offsetAndMetadata: OffsetAndMetadata, maxVersion: Short = 3): Array[Byte] = {
- val version =
- if (offsetAndMetadata.expireTimestampMs.isPresent) Math.min(1, maxVersion).toShort
- else maxVersion
- MessageUtil.toVersionPrefixedBytes(version, new OffsetCommitValue()
- .setOffset(offsetAndMetadata.committedOffset)
- .setMetadata(offsetAndMetadata.metadata)
- .setCommitTimestamp(offsetAndMetadata.commitTimestampMs)
- .setLeaderEpoch(offsetAndMetadata.leaderEpoch.orElse(RecordBatch.NO_PARTITION_LEADER_EPOCH))
- // version 1 has a non empty expireTimestamp field
- .setExpireTimestamp(offsetAndMetadata.expireTimestampMs.orElse(OffsetCommitRequest.DEFAULT_TIMESTAMP))
- )
- }
-
- /**
- * Generates the payload for group metadata message from given offset and metadata
- * assuming the generation id, selected protocol, leader and member assignment are all available
- *
- * @param groupMetadata current group metadata
- * @param assignment the assignment for the rebalancing generation
- * @param version the version to serialize it with, the default is `3`, the highest supported non-flexible version
- * until a tagged field is introduced or the version is bumped. The default should always be used
- * outside of tests
- * @return payload for offset commit message
- */
- def groupMetadataValue(groupMetadata: GroupMetadata,
- assignment: Map[String, Array[Byte]],
- version: Short = 3): Array[Byte] = {
- MessageUtil.toVersionPrefixedBytes(version, new GroupMetadataValue()
- .setProtocolType(groupMetadata.protocolType.getOrElse(""))
- .setGeneration(groupMetadata.generationId)
- .setProtocol(groupMetadata.protocolName.orNull)
- .setLeader(groupMetadata.leaderOrNull)
- .setCurrentStateTimestamp(groupMetadata.currentStateTimestampOrDefault)
- .setMembers(groupMetadata.allMemberMetadata.map { memberMetadata =>
- new GroupMetadataValue.MemberMetadata()
- .setMemberId(memberMetadata.memberId)
- .setClientId(memberMetadata.clientId)
- .setClientHost(memberMetadata.clientHost)
- .setSessionTimeout(memberMetadata.sessionTimeoutMs)
- .setRebalanceTimeout(memberMetadata.rebalanceTimeoutMs)
- .setGroupInstanceId(memberMetadata.groupInstanceId.orNull)
- // The group is non-empty, so the current protocol must be defined
- .setSubscription(groupMetadata.protocolName.map(memberMetadata.metadata)
- .getOrElse(throw new IllegalStateException("Attempted to write non-empty group metadata with no defined protocol.")))
- .setAssignment(assignment.getOrElse(memberMetadata.memberId,
- throw new IllegalStateException(s"Attempted to write member ${memberMetadata.memberId} of group ${groupMetadata.groupId} with no assignment.")))
- }.asJava))
- }
-
- /**
- * Decodes the offset messages' key
- *
- * @param buffer input byte-buffer
- * @return an OffsetKey or GroupMetadataKey object from the message
- */
- def readMessageKey(buffer: ByteBuffer): BaseKey = {
- val version = buffer.getShort
- try {
- CoordinatorRecordType.fromId(version) match {
- case CoordinatorRecordType.LEGACY_OFFSET_COMMIT =>
- // version 0 refers to the legacy offset commit.
- val key = new LegacyOffsetCommitKey(new ByteBufferAccessor(buffer), 0.toShort)
- OffsetKey(version, GroupTopicPartition(key.group, new TopicPartition(key.topic, key.partition)))
-
- case CoordinatorRecordType.OFFSET_COMMIT =>
- // version 1 refers to offset commit.
- val key = new OffsetCommitKey(new ByteBufferAccessor(buffer), 0.toShort)
- OffsetKey(version, GroupTopicPartition(key.group, new TopicPartition(key.topic, key.partition)))
-
- case CoordinatorRecordType.GROUP_METADATA =>
- // version 2 refers to group metadata.
- val key = new GroupMetadataKeyData(new ByteBufferAccessor(buffer), 0.toShort)
- GroupMetadataKey(version, key.group)
-
- case _ =>
- UnknownKey(version)
- }
- } catch {
- case _: UnsupportedVersionException => UnknownKey(version)
- }
- }
-
- /**
- * Decodes the offset messages' payload and retrieves offset and metadata from it
- *
- * @param buffer input byte-buffer
- * @return an offset-metadata object from the message
- */
- def readOffsetMessageValue(buffer: ByteBuffer): OffsetAndMetadata = {
- // tombstone
- if (buffer == null) null
- else {
- val version = buffer.getShort
- if (version >= OffsetCommitValue.LOWEST_SUPPORTED_VERSION && version <= OffsetCommitValue.HIGHEST_SUPPORTED_VERSION) {
- val value = new OffsetCommitValue(new ByteBufferAccessor(buffer), version)
- new OffsetAndMetadata(
- value.offset,
- if (value.leaderEpoch == RecordBatch.NO_PARTITION_LEADER_EPOCH) OptionalInt.empty() else OptionalInt.of(value.leaderEpoch),
- value.metadata,
- value.commitTimestamp,
- if (value.expireTimestamp == OffsetCommitRequest.DEFAULT_TIMESTAMP) OptionalLong.empty() else OptionalLong.of(value.expireTimestamp))
- } else throw new IllegalStateException(s"Unknown offset message version: $version")
- }
- }
-
- /**
- * Decodes the group metadata messages' payload and retrieves its member metadata from it
- *
- * @param groupId The ID of the group to be read
- * @param buffer input byte-buffer
- * @param time the time instance to use
- * @return a group metadata object from the message
- */
- def readGroupMessageValue(groupId: String, buffer: ByteBuffer, time: Time): GroupMetadata = {
- // tombstone
- if (buffer == null) null
- else {
- val version = buffer.getShort
- if (version >= GroupMetadataValue.LOWEST_SUPPORTED_VERSION && version <= GroupMetadataValue.HIGHEST_SUPPORTED_VERSION) {
- val value = new GroupMetadataValue(new ByteBufferAccessor(buffer), version)
- val members = value.members.asScala.map { memberMetadata =>
- new MemberMetadata(
- memberId = memberMetadata.memberId,
- groupInstanceId = Option(memberMetadata.groupInstanceId),
- clientId = memberMetadata.clientId,
- clientHost = memberMetadata.clientHost,
- rebalanceTimeoutMs = if (version == 0) memberMetadata.sessionTimeout else memberMetadata.rebalanceTimeout,
- sessionTimeoutMs = memberMetadata.sessionTimeout,
- protocolType = value.protocolType,
- supportedProtocols = List((value.protocol, memberMetadata.subscription)),
- assignment = memberMetadata.assignment)
- }
- GroupMetadata.loadGroup(
- groupId = groupId,
- initialState = if (members.isEmpty) Empty else Stable,
- generationId = value.generation,
- protocolType = value.protocolType,
- protocolName = value.protocol,
- leaderId = value.leader,
- currentStateTimestamp = if (value.currentStateTimestamp == -1) None else Some(value.currentStateTimestamp),
- members = members,
- time = time)
- } else throw new IllegalStateException(s"Unknown group metadata message version: $version")
- }
- }
-
- def maybeConvertOffsetCommitError(error: Errors) : Errors = {
- error match {
- case Errors.NETWORK_EXCEPTION =>
- // When committing offsets transactionally, we now verify the transaction with the
- // transaction coordinator. Verification can fail with `NETWORK_EXCEPTION`, a retriable
- // error which older clients may not expect and retry correctly. We translate the error to
- // `COORDINATOR_LOAD_IN_PROGRESS` because it causes clients to retry the request without an
- // unnecessary coordinator lookup.
- Errors.COORDINATOR_LOAD_IN_PROGRESS
-
- case Errors.UNKNOWN_TOPIC_OR_PARTITION
- | Errors.NOT_ENOUGH_REPLICAS
- | Errors.NOT_ENOUGH_REPLICAS_AFTER_APPEND =>
- Errors.COORDINATOR_NOT_AVAILABLE
-
- case Errors.NOT_LEADER_OR_FOLLOWER
- | Errors.KAFKA_STORAGE_ERROR =>
- Errors.NOT_COORDINATOR
-
- case Errors.MESSAGE_TOO_LARGE
- | Errors.RECORD_LIST_TOO_LARGE
- | Errors.INVALID_FETCH_SIZE =>
- Errors.INVALID_COMMIT_OFFSET_SIZE
-
- // We may see INVALID_TXN_STATE or INVALID_PID_MAPPING here due to transaction verification.
- // They can be returned without mapping to a new error.
- case other => other
- }
- }
-
-}
-
-case class GroupTopicPartition(group: String, topicPartition: TopicPartition) {
-
- def this(group: String, topic: String, partition: Int) =
- this(group, new TopicPartition(topic, partition))
-
- override def toString: String =
- "[%s,%s,%d]".format(group, topicPartition.topic, topicPartition.partition)
-}
-
-sealed trait BaseKey{
- def version: Short
- def key: Any
-}
-
-case class OffsetKey(version: Short, key: GroupTopicPartition) extends BaseKey {
- override def toString: String = key.toString
-}
-
-case class GroupMetadataKey(version: Short, key: String) extends BaseKey {
- override def toString: String = key
-}
-
-case class UnknownKey(version: Short) extends BaseKey {
- override def key: String = null
- override def toString: String = key
-}
diff --git a/core/src/main/scala/kafka/coordinator/group/MemberMetadata.scala b/core/src/main/scala/kafka/coordinator/group/MemberMetadata.scala
deleted file mode 100644
index 6ad62739770..00000000000
--- a/core/src/main/scala/kafka/coordinator/group/MemberMetadata.scala
+++ /dev/null
@@ -1,153 +0,0 @@
-/**
- * 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 kafka.coordinator.group
-
-import java.util
-
-import kafka.utils.nonthreadsafe
-
-case class MemberSummary(memberId: String,
- groupInstanceId: Option[String],
- clientId: String,
- clientHost: String,
- metadata: Array[Byte],
- assignment: Array[Byte])
-
-private object MemberMetadata {
- def plainProtocolSet(supportedProtocols: List[(String, Array[Byte])]): Set[String] = supportedProtocols.map(_._1).toSet
-}
-
-/**
- * Member metadata contains the following metadata:
- *
- * Heartbeat metadata:
- * 1. negotiated heartbeat session timeout
- * 2. timestamp of the latest heartbeat
- *
- * Protocol metadata:
- * 1. the list of supported protocols (ordered by preference)
- * 2. the metadata associated with each protocol
- *
- * In addition, it also contains the following state information:
- *
- * 1. Awaiting rebalance callback: when the group is in the prepare-rebalance state,
- * its rebalance callback will be kept in the metadata if the
- * member has sent the join group request
- * 2. Awaiting sync callback: when the group is in the awaiting-sync state, its sync callback
- * is kept in metadata until the leader provides the group assignment
- * and the group transitions to stable
- */
-@nonthreadsafe
-private[group] class MemberMetadata(var memberId: String,
- val groupInstanceId: Option[String],
- val clientId: String,
- val clientHost: String,
- var rebalanceTimeoutMs: Int,
- var sessionTimeoutMs: Int,
- val protocolType: String,
- var supportedProtocols: List[(String, Array[Byte])],
- var assignment: Array[Byte] = Array.empty[Byte]) {
-
- var awaitingJoinCallback: JoinGroupResult => Unit = _
- var awaitingSyncCallback: SyncGroupResult => Unit = _
- var isNew: Boolean = false
-
- def isStaticMember: Boolean = groupInstanceId.isDefined
-
- // This variable is used to track heartbeat completion through the delayed
- // heartbeat purgatory. When scheduling a new heartbeat expiration, we set
- // this value to `false`. Upon receiving the heartbeat (or any other event
- // indicating the liveness of the client), we set it to `true` so that the
- // delayed heartbeat can be completed.
- var heartbeatSatisfied: Boolean = false
-
- def isAwaitingJoin: Boolean = awaitingJoinCallback != null
- def isAwaitingSync: Boolean = awaitingSyncCallback != null
-
- /**
- * Get metadata corresponding to the provided protocol.
- */
- def metadata(protocol: String): Array[Byte] = {
- supportedProtocols.find(_._1 == protocol) match {
- case Some((_, metadata)) => metadata
- case None =>
- throw new IllegalArgumentException("Member does not support protocol")
- }
- }
-
- def hasSatisfiedHeartbeat: Boolean = {
- if (isNew) {
- // New members can be expired while awaiting join, so we have to check this first
- heartbeatSatisfied
- } else if (isAwaitingJoin || isAwaitingSync) {
- // Members that are awaiting a rebalance automatically satisfy expected heartbeats
- true
- } else {
- // Otherwise we require the next heartbeat
- heartbeatSatisfied
- }
- }
-
- /**
- * Check if the provided protocol metadata matches the currently stored metadata.
- */
- def matches(protocols: List[(String, Array[Byte])]): Boolean = {
- if (protocols.size != this.supportedProtocols.size)
- return false
-
- for (i <- protocols.indices) {
- val p1 = protocols(i)
- val p2 = supportedProtocols(i)
- if (p1._1 != p2._1 || !util.Arrays.equals(p1._2, p2._2))
- return false
- }
- true
- }
-
- def summary(protocol: String): MemberSummary = {
- MemberSummary(memberId, groupInstanceId, clientId, clientHost, metadata(protocol), assignment)
- }
-
- def summaryNoMetadata(): MemberSummary = {
- MemberSummary(memberId, groupInstanceId, clientId, clientHost, Array.empty[Byte], Array.empty[Byte])
- }
-
- /**
- * Vote for one of the potential group protocols. This takes into account the protocol preference as
- * indicated by the order of supported protocols and returns the first one also contained in the set
- */
- def vote(candidates: Set[String]): String = {
- supportedProtocols.find({ case (protocol, _) => candidates.contains(protocol)}) match {
- case Some((protocol, _)) => protocol
- case None =>
- throw new IllegalArgumentException("Member does not support any of the candidate protocols")
- }
- }
-
- override def toString: String = {
- "MemberMetadata(" +
- s"memberId=$memberId, " +
- s"groupInstanceId=$groupInstanceId, " +
- s"clientId=$clientId, " +
- s"clientHost=$clientHost, " +
- s"sessionTimeoutMs=$sessionTimeoutMs, " +
- s"rebalanceTimeoutMs=$rebalanceTimeoutMs, " +
- s"supportedProtocols=${supportedProtocols.map(_._1)}" +
- ")"
- }
-}
diff --git a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
deleted file mode 100644
index d4c4e52f70e..00000000000
--- a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
+++ /dev/null
@@ -1,987 +0,0 @@
-/**
- * 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 kafka.coordinator.group
-
-import kafka.coordinator.group.GroupCoordinatorConcurrencyTest.{JoinGroupCallback, SyncGroupCallback}
-import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
-import org.apache.kafka.common.errors.{InvalidGroupIdException, UnsupportedVersionException}
-import org.apache.kafka.common.message.{ConsumerGroupHeartbeatRequestData, DeleteGroupsResponseData, DescribeGroupsResponseData, DescribeShareGroupOffsetsRequestData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, OffsetFetchRequestData, OffsetFetchResp [...]
-import org.apache.kafka.common.message.JoinGroupRequestData.JoinGroupRequestProtocol
-import org.apache.kafka.common.message.JoinGroupResponseData.JoinGroupResponseMember
-import org.apache.kafka.common.message.OffsetDeleteRequestData.{OffsetDeleteRequestPartition, OffsetDeleteRequestTopic, OffsetDeleteRequestTopicCollection}
-import org.apache.kafka.common.message.OffsetDeleteResponseData.{OffsetDeleteResponsePartition, OffsetDeleteResponsePartitionCollection, OffsetDeleteResponseTopic, OffsetDeleteResponseTopicCollection}
-import org.apache.kafka.common.network.{ClientInformation, ListenerName}
-import org.apache.kafka.common.protocol.{ApiKeys, Errors}
-import org.apache.kafka.common.requests.{OffsetFetchResponse, RequestContext, RequestHeader, TransactionResult}
-import org.apache.kafka.common.security.auth.{KafkaPrincipal, SecurityProtocol}
-import org.apache.kafka.common.utils.{BufferSupplier, Time}
-import org.apache.kafka.common.utils.annotation.ApiKeyVersionsSource
-import org.apache.kafka.coordinator.group.OffsetAndMetadata
-import org.apache.kafka.server.common.RequestLocal
-import org.apache.kafka.server.util.MockTime
-import org.apache.kafka.test.TestUtils.assertFutureThrows
-import org.junit.jupiter.api.Assertions.{assertEquals, assertFalse, assertTrue}
-import org.junit.jupiter.api.Test
-import org.junit.jupiter.params.ParameterizedTest
-import org.mockito.ArgumentMatchers.any
-import org.mockito.{ArgumentCaptor, ArgumentMatchers}
-import org.mockito.Mockito.{mock, verify, when}
-
-import java.net.InetAddress
-import java.util.{Optional, OptionalInt, OptionalLong}
-import scala.jdk.CollectionConverters._
-
-class GroupCoordinatorAdapterTest {
-
- private def makeContext(
- apiKey: ApiKeys,
- apiVersion: Short
- ): RequestContext = {
- new RequestContext(
- new RequestHeader(apiKey, apiVersion, "client", 0),
- "1",
- InetAddress.getLocalHost,
- KafkaPrincipal.ANONYMOUS,
- ListenerName.forSecurityProtocol(SecurityProtocol.PLAINTEXT),
- SecurityProtocol.PLAINTEXT,
- ClientInformation.EMPTY,
- false
- )
- }
-
- @Test
- def testJoinConsumerGroup(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- val ctx = makeContext(ApiKeys.CONSUMER_GROUP_HEARTBEAT, ApiKeys.CONSUMER_GROUP_HEARTBEAT.latestVersion)
- val request = new ConsumerGroupHeartbeatRequestData()
- .setGroupId("group")
-
- val future = adapter.consumerGroupHeartbeat(ctx, request)
-
- assertTrue(future.isDone)
- assertTrue(future.isCompletedExceptionally)
- assertFutureThrows(classOf[UnsupportedVersionException], future)
- }
-
- @Test
- def testStreamsGroupHeartbeat(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- val ctx = makeContext(ApiKeys.STREAMS_GROUP_HEARTBEAT, ApiKeys.STREAMS_GROUP_HEARTBEAT.latestVersion)
- val request = new StreamsGroupHeartbeatRequestData()
- .setGroupId("group")
-
- val future = adapter.streamsGroupHeartbeat(ctx, request)
-
- assertTrue(future.isDone)
- assertTrue(future.isCompletedExceptionally)
- assertFutureThrows(classOf[UnsupportedVersionException], future)
- }
-
- @Test
- def testJoinShareGroup(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- val ctx = makeContext(ApiKeys.SHARE_GROUP_HEARTBEAT, ApiKeys.SHARE_GROUP_HEARTBEAT.latestVersion)
- val request = new ShareGroupHeartbeatRequestData()
- .setGroupId("group")
-
- val future = adapter.shareGroupHeartbeat(ctx, request)
-
- assertTrue(future.isDone)
- assertTrue(future.isCompletedExceptionally)
- assertFutureThrows(classOf[UnsupportedVersionException], future)
- }
-
- @Test
- def testDescribeShareGroupOffsets(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- val context = makeContext(ApiKeys.DESCRIBE_SHARE_GROUP_OFFSETS, ApiKeys.DESCRIBE_SHARE_GROUP_OFFSETS.latestVersion)
- val request = new DescribeShareGroupOffsetsRequestData.DescribeShareGroupOffsetsRequestGroup()
- .setGroupId("group")
-
- val future = adapter.describeShareGroupOffsets(context, request)
-
- assertTrue(future.isDone)
- assertTrue(future.isCompletedExceptionally)
- assertFutureThrows(classOf[UnsupportedVersionException], future)
- }
-
- @ParameterizedTest
- @ApiKeyVersionsSource(apiKey = ApiKeys.JOIN_GROUP)
- def testJoinGroup(version: Short): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- val ctx = makeContext(ApiKeys.JOIN_GROUP, version)
- val request = new JoinGroupRequestData()
- .setGroupId("group")
- .setMemberId("member")
- .setProtocolType("consumer")
- .setRebalanceTimeoutMs(1000)
- .setSessionTimeoutMs(2000)
- .setReason("reason")
- .setProtocols(new JoinGroupRequestData.JoinGroupRequestProtocolCollection(List(
- new JoinGroupRequestProtocol()
- .setName("first")
- .setMetadata("first".getBytes()),
- new JoinGroupRequestProtocol()
- .setName("second")
- .setMetadata("second".getBytes())).iterator.asJava))
- val bufferSupplier = BufferSupplier.create()
-
- val future = adapter.joinGroup(ctx, request, bufferSupplier)
- assertFalse(future.isDone)
-
- val capturedProtocols: ArgumentCaptor[List[(String, Array[Byte])]] =
- ArgumentCaptor.forClass(classOf[List[(String, Array[Byte])]])
- val capturedCallback: ArgumentCaptor[JoinGroupCallback] =
- ArgumentCaptor.forClass(classOf[JoinGroupCallback])
-
- verify(groupCoordinator).handleJoinGroup(
- ArgumentMatchers.eq(request.groupId),
- ArgumentMatchers.eq(request.memberId),
- ArgumentMatchers.eq(None),
- ArgumentMatchers.eq(if (version >= 4) true else false),
- ArgumentMatchers.eq(if (version >= 9) true else false),
- ArgumentMatchers.eq(ctx.clientId),
- ArgumentMatchers.eq(InetAddress.getLocalHost.toString),
- ArgumentMatchers.eq(request.rebalanceTimeoutMs),
- ArgumentMatchers.eq(request.sessionTimeoutMs),
- ArgumentMatchers.eq(request.protocolType),
- capturedProtocols.capture(),
- capturedCallback.capture(),
- ArgumentMatchers.eq(Some("reason")),
- ArgumentMatchers.eq(new RequestLocal(bufferSupplier))
- )
-
- assertEquals(List(
- ("first", "first"),
- ("second", "second")
- ), capturedProtocols.getValue.map { case (name, metadata) =>
- (name, new String(metadata))
- })
-
- capturedCallback.getValue.apply(JoinGroupResult(
- members = List(
- new JoinGroupResponseMember()
- .setMemberId("member")
- .setMetadata("member".getBytes())
- .setGroupInstanceId("instance")
- ),
- memberId = "member",
- generationId = 10,
- protocolType = Some("consumer"),
- protocolName = Some("range"),
- leaderId = "leader",
- skipAssignment = true,
- error = Errors.UNKNOWN_MEMBER_ID
- ))
-
- val expectedData = new JoinGroupResponseData()
- .setMembers(List(new JoinGroupResponseMember()
- .setMemberId("member")
- .setMetadata("member".getBytes())
- .setGroupInstanceId("instance")).asJava)
- .setMemberId("member")
- .setGenerationId(10)
- .setProtocolType("consumer")
- .setProtocolName("range")
- .setLeader("leader")
- .setSkipAssignment(true)
- .setErrorCode(Errors.UNKNOWN_MEMBER_ID.code)
-
- assertTrue(future.isDone)
- assertEquals(expectedData, future.get())
- }
-
- @ParameterizedTest
- @ApiKeyVersionsSource(apiKey = ApiKeys.SYNC_GROUP)
- def testSyncGroup(version: Short): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- val ctx = makeContext(ApiKeys.SYNC_GROUP, version)
- val data = new SyncGroupRequestData()
- .setGroupId("group")
- .setMemberId("member1")
- .setGroupInstanceId("instance")
- .setProtocolType("consumer")
- .setProtocolName("range")
- .setGenerationId(10)
- .setAssignments(List(
- new SyncGroupRequestData.SyncGroupRequestAssignment()
- .setMemberId("member1")
- .setAssignment("member1".getBytes()),
- new SyncGroupRequestData.SyncGroupRequestAssignment()
- .setMemberId("member2")
- .setAssignment("member2".getBytes())
- ).asJava)
- val bufferSupplier = BufferSupplier.create()
-
- val future = adapter.syncGroup(ctx, data, bufferSupplier)
- assertFalse(future.isDone)
-
- val capturedAssignment: ArgumentCaptor[Map[String, Array[Byte]]] =
- ArgumentCaptor.forClass(classOf[Map[String, Array[Byte]]])
- val capturedCallback: ArgumentCaptor[SyncGroupCallback] =
- ArgumentCaptor.forClass(classOf[SyncGroupCallback])
-
- verify(groupCoordinator).handleSyncGroup(
- ArgumentMatchers.eq(data.groupId),
- ArgumentMatchers.eq(data.generationId),
- ArgumentMatchers.eq(data.memberId),
- ArgumentMatchers.eq(Some(data.protocolType)),
- ArgumentMatchers.eq(Some(data.protocolName)),
- ArgumentMatchers.eq(Some(data.groupInstanceId)),
- capturedAssignment.capture(),
- capturedCallback.capture(),
- ArgumentMatchers.eq(new RequestLocal(bufferSupplier))
- )
-
- assertEquals(Map(
- "member1" -> "member1",
- "member2" -> "member2",
- ), capturedAssignment.getValue.map { case (member, metadata) =>
- (member, new String(metadata))
- })
-
- capturedCallback.getValue.apply(SyncGroupResult(
- error = Errors.NONE,
- protocolType = Some("consumer"),
- protocolName = Some("range"),
- memberAssignment = "member1".getBytes()
- ))
-
- val expectedResponseData = new SyncGroupResponseData()
- .setErrorCode(Errors.NONE.code)
- .setProtocolType("consumer")
- .setProtocolName("range")
- .setAssignment("member1".getBytes())
-
- assertTrue(future.isDone)
- assertEquals(expectedResponseData, future.get())
- }
-
- @Test
- def testHeartbeat(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- val ctx = makeContext(ApiKeys.HEARTBEAT, ApiKeys.HEARTBEAT.latestVersion)
- val data = new HeartbeatRequestData()
- .setGroupId("group")
- .setMemberId("member1")
- .setGenerationId(0)
-
- val future = adapter.heartbeat(ctx, data)
-
- val capturedCallback: ArgumentCaptor[Errors => Unit] =
- ArgumentCaptor.forClass(classOf[Errors => Unit])
-
- verify(groupCoordinator).handleHeartbeat(
- ArgumentMatchers.eq(data.groupId),
- ArgumentMatchers.eq(data.memberId),
- ArgumentMatchers.eq(None),
- ArgumentMatchers.eq(data.generationId),
- capturedCallback.capture(),
- )
-
- assertFalse(future.isDone)
-
- capturedCallback.getValue.apply(Errors.NONE)
-
- assertTrue(future.isDone)
- assertEquals(new HeartbeatResponseData(), future.get())
- }
-
- def testLeaveGroup(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- val ctx = makeContext(ApiKeys.LEAVE_GROUP, ApiKeys.LEAVE_GROUP.latestVersion)
- val data = new LeaveGroupRequestData()
- .setGroupId("group")
- .setMembers(List(
- new LeaveGroupRequestData.MemberIdentity()
- .setMemberId("member-1")
- .setGroupInstanceId("instance-1"),
- new LeaveGroupRequestData.MemberIdentity()
- .setMemberId("member-2")
- .setGroupInstanceId("instance-2")
- ).asJava)
-
- val future = adapter.leaveGroup(ctx, data)
-
- val capturedCallback: ArgumentCaptor[LeaveGroupResult => Unit] =
- ArgumentCaptor.forClass(classOf[LeaveGroupResult => Unit])
-
- verify(groupCoordinator).handleLeaveGroup(
- ArgumentMatchers.eq(data.groupId),
- ArgumentMatchers.eq(data.members.asScala.toList),
- capturedCallback.capture(),
- )
-
- assertFalse(future.isDone)
-
- capturedCallback.getValue.apply(LeaveGroupResult(
- topLevelError = Errors.NONE,
- memberResponses = List(
- LeaveMemberResponse(
- memberId = "member-1",
- groupInstanceId = Some("instance-1"),
- error = Errors.NONE
- ),
- LeaveMemberResponse(
- memberId = "member-2",
- groupInstanceId = Some("instance-2"),
- error = Errors.NONE
- )
- )
- ))
-
- val expectedData = new LeaveGroupResponseData()
- .setMembers(List(
- new LeaveGroupResponseData.MemberResponse()
- .setMemberId("member-1")
- .setGroupInstanceId("instance-1"),
- new LeaveGroupResponseData.MemberResponse()
- .setMemberId("member-2")
- .setGroupInstanceId("instance-2")
- ).asJava)
-
- assertTrue(future.isDone)
- assertEquals(expectedData, future.get())
- }
-
- @Test
- def testListGroups(): Unit = {
- testListGroups(null, null, Set.empty, Set.empty)
- testListGroups(List(), List(), Set.empty, Set.empty)
- testListGroups(List("Stable, Empty"), List(), Set("Stable, Empty"), Set.empty)
- testListGroups(List(), List("classic"), Set.empty, Set("classic"))
- }
-
- def testListGroups(
- statesFilter: List[String],
- typesFilter: List[String],
- expectedStatesFilter: Set[String],
- expectedTypesFilter: Set[String]
- ): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- val ctx = makeContext(ApiKeys.LIST_GROUPS, ApiKeys.LIST_GROUPS.latestVersion)
- val data = new ListGroupsRequestData()
- .setStatesFilter(statesFilter.asJava)
- .setTypesFilter(typesFilter.asJava)
-
- when(groupCoordinator.handleListGroups(expectedStatesFilter, expectedTypesFilter)).thenReturn {
- (Errors.NOT_COORDINATOR, List(
- GroupOverview("group1", "protocol1", "Stable", "classic"),
- GroupOverview("group2", "qwerty", "Empty", "classic")
- ))
- }
-
- val future = adapter.listGroups(ctx, data)
- assertTrue(future.isDone)
-
- val expectedData = new ListGroupsResponseData()
- .setErrorCode(Errors.NOT_COORDINATOR.code)
- .setGroups(List(
- new ListGroupsResponseData.ListedGroup()
- .setGroupId("group1")
- .setProtocolType("protocol1")
- .setGroupState("Stable")
- .setGroupType("classic"),
- new ListGroupsResponseData.ListedGroup()
- .setGroupId("group2")
- .setProtocolType("qwerty")
- .setGroupState("Empty")
- .setGroupType("classic")
- ).asJava)
-
- assertTrue(future.isDone)
- assertEquals(expectedData, future.get())
- }
-
- @Test
- def testDescribeGroup(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- val groupId1 = "group-1"
- val groupId2 = "group-2"
-
- val groupSummary1 = GroupSummary(
- "Stable",
- "consumer",
- "roundrobin",
- List(MemberSummary(
- "memberid",
- Some("instanceid"),
- "clientid",
- "clienthost",
- "metadata".getBytes(),
- "assignment".getBytes()
- ))
- )
-
- when(groupCoordinator.handleDescribeGroup(groupId1, ApiKeys.DESCRIBE_GROUPS.latestVersion)).thenReturn {
- (Errors.NONE, None, groupSummary1)
- }
-
- when(groupCoordinator.handleDescribeGroup(groupId2, ApiKeys.DESCRIBE_GROUPS.latestVersion)).thenReturn {
- (Errors.NOT_COORDINATOR, None, GroupCoordinator.EmptyGroup)
- }
-
- val ctx = makeContext(ApiKeys.DESCRIBE_GROUPS, ApiKeys.DESCRIBE_GROUPS.latestVersion)
- val future = adapter.describeGroups(ctx, List(groupId1, groupId2).asJava)
- assertTrue(future.isDone)
-
- val expectedDescribedGroups = List(
- new DescribeGroupsResponseData.DescribedGroup()
- .setGroupId(groupId1)
- .setErrorCode(Errors.NONE.code)
- .setProtocolType(groupSummary1.protocolType)
- .setProtocolData(groupSummary1.protocol)
- .setGroupState(groupSummary1.state)
- .setMembers(List(new DescribeGroupsResponseData.DescribedGroupMember()
- .setMemberId(groupSummary1.members.head.memberId)
- .setGroupInstanceId(groupSummary1.members.head.groupInstanceId.orNull)
- .setClientId(groupSummary1.members.head.clientId)
- .setClientHost(groupSummary1.members.head.clientHost)
- .setMemberMetadata(groupSummary1.members.head.metadata)
- .setMemberAssignment(groupSummary1.members.head.assignment)
- ).asJava),
- new DescribeGroupsResponseData.DescribedGroup()
- .setGroupId(groupId2)
- .setErrorCode(Errors.NOT_COORDINATOR.code)
- ).asJava
-
- assertEquals(expectedDescribedGroups, future.get())
- }
-
- @Test
- def testDeleteGroups(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- val ctx = makeContext(ApiKeys.DELETE_GROUPS, ApiKeys.DELETE_GROUPS.latestVersion)
- val groupIds = List("group-1", "group-2", "group-3")
- val bufferSupplier = BufferSupplier.create()
-
- when(groupCoordinator.handleDeleteGroups(
- groupIds.toSet,
- new RequestLocal(bufferSupplier)
- )).thenReturn(Map(
- "group-1" -> Errors.NONE,
- "group-2" -> Errors.NOT_COORDINATOR,
- "group-3" -> Errors.INVALID_GROUP_ID,
- ))
-
- val future = adapter.deleteGroups(ctx, groupIds.asJava, bufferSupplier)
- assertTrue(future.isDone)
-
- val expectedResults = new DeleteGroupsResponseData.DeletableGroupResultCollection()
- expectedResults.add(new DeleteGroupsResponseData.DeletableGroupResult()
- .setGroupId("group-1")
- .setErrorCode(Errors.NONE.code))
- expectedResults.add(new DeleteGroupsResponseData.DeletableGroupResult()
- .setGroupId("group-2")
- .setErrorCode(Errors.NOT_COORDINATOR.code))
- expectedResults.add(new DeleteGroupsResponseData.DeletableGroupResult()
- .setGroupId("group-3")
- .setErrorCode(Errors.INVALID_GROUP_ID.code))
-
- assertEquals(expectedResults, future.get())
- }
-
- @Test
- def testFetchAllOffsets(): Unit = {
- val foo0 = new TopicPartition("foo", 0)
- val foo1 = new TopicPartition("foo", 1)
- val bar1 = new TopicPartition("bar", 1)
-
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- when(groupCoordinator.handleFetchOffsets(
- "group",
- requireStable = true,
- None
- )).thenReturn((
- Errors.NONE,
- Map(
- foo0 -> new OffsetFetchResponse.PartitionData(
- 100,
- Optional.of(1),
- "foo",
- Errors.NONE
- ),
- bar1 -> new OffsetFetchResponse.PartitionData(
- -1,
- Optional.empty[Integer],
- "",
- Errors.UNKNOWN_TOPIC_OR_PARTITION
- ),
- foo1 -> new OffsetFetchResponse.PartitionData(
- 200,
- Optional.empty[Integer],
- "",
- Errors.NONE
- ),
- )
- ))
-
- val ctx = makeContext(ApiKeys.OFFSET_FETCH, ApiKeys.OFFSET_FETCH.latestVersion)
- val future = adapter.fetchAllOffsets(
- ctx,
- new OffsetFetchRequestData.OffsetFetchRequestGroup().setGroupId("group"),
- requireStable = true
- )
-
- assertTrue(future.isDone)
-
- val expectedResponse = List(
- new OffsetFetchResponseData.OffsetFetchResponseTopics()
- .setName(foo0.topic)
- .setPartitions(List(
- new OffsetFetchResponseData.OffsetFetchResponsePartitions()
- .setPartitionIndex(foo0.partition)
- .setCommittedOffset(100)
- .setCommittedLeaderEpoch(1)
- .setMetadata("foo")
- .setErrorCode(Errors.NONE.code),
- new OffsetFetchResponseData.OffsetFetchResponsePartitions()
- .setPartitionIndex(foo1.partition)
- .setCommittedOffset(200)
- .setCommittedLeaderEpoch(-1)
- .setMetadata("")
- .setErrorCode(Errors.NONE.code),
- ).asJava),
- new OffsetFetchResponseData.OffsetFetchResponseTopics()
- .setName(bar1.topic)
- .setPartitions(List(
- new OffsetFetchResponseData.OffsetFetchResponsePartitions()
- .setPartitionIndex(bar1.partition)
- .setCommittedOffset(-1)
- .setCommittedLeaderEpoch(-1)
- .setMetadata("")
- .setErrorCode(Errors.UNKNOWN_TOPIC_OR_PARTITION.code)
- ).asJava)
- )
-
- assertEquals("group", future.get().groupId)
- assertEquals(
- expectedResponse.sortWith(_.name > _.name),
- future.get().topics.asScala.toList.sortWith(_.name > _.name)
- )
- }
-
- @Test
- def testFetchOffsets(): Unit = {
- val foo0 = new TopicPartition("foo", 0)
- val foo1 = new TopicPartition("foo", 1)
- val bar1 = new TopicPartition("bar", 1)
-
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- when(groupCoordinator.handleFetchOffsets(
- "group",
- requireStable = true,
- Some(Seq(foo0, foo1, bar1))
- )).thenReturn((
- Errors.NONE,
- Map(
- foo0 -> new OffsetFetchResponse.PartitionData(
- 100,
- Optional.of(1),
- "foo",
- Errors.NONE
- ),
- bar1 -> new OffsetFetchResponse.PartitionData(
- -1,
- Optional.empty[Integer],
- "",
- Errors.UNKNOWN_TOPIC_OR_PARTITION
- ),
- foo1 -> new OffsetFetchResponse.PartitionData(
- 200,
- Optional.empty[Integer],
- "",
- Errors.NONE
- ),
- )
- ))
-
- val ctx = makeContext(ApiKeys.OFFSET_FETCH, ApiKeys.OFFSET_FETCH.latestVersion)
- val future = adapter.fetchOffsets(
- ctx,
- new OffsetFetchRequestData.OffsetFetchRequestGroup()
- .setGroupId("group")
- .setTopics(List(
- new OffsetFetchRequestData.OffsetFetchRequestTopics()
- .setName(foo0.topic)
- .setPartitionIndexes(List[Integer](foo0.partition, foo1.partition).asJava),
- new OffsetFetchRequestData.OffsetFetchRequestTopics()
- .setName(bar1.topic)
- .setPartitionIndexes(List[Integer](bar1.partition).asJava)).asJava),
- requireStable = true
- )
-
- assertTrue(future.isDone)
-
- val expectedResponse = List(
- new OffsetFetchResponseData.OffsetFetchResponseTopics()
- .setName(foo0.topic)
- .setPartitions(List(
- new OffsetFetchResponseData.OffsetFetchResponsePartitions()
- .setPartitionIndex(foo0.partition)
- .setCommittedOffset(100)
- .setCommittedLeaderEpoch(1)
- .setMetadata("foo")
- .setErrorCode(Errors.NONE.code),
- new OffsetFetchResponseData.OffsetFetchResponsePartitions()
- .setPartitionIndex(foo1.partition)
- .setCommittedOffset(200)
- .setCommittedLeaderEpoch(-1)
- .setMetadata("")
- .setErrorCode(Errors.NONE.code),
- ).asJava),
- new OffsetFetchResponseData.OffsetFetchResponseTopics()
- .setName(bar1.topic)
- .setPartitions(List(
- new OffsetFetchResponseData.OffsetFetchResponsePartitions()
- .setPartitionIndex(bar1.partition)
- .setCommittedOffset(-1)
- .setCommittedLeaderEpoch(-1)
- .setMetadata("")
- .setErrorCode(Errors.UNKNOWN_TOPIC_OR_PARTITION.code)
- ).asJava)
- )
-
- assertEquals("group", future.get().groupId)
- assertEquals(
- expectedResponse.sortWith(_.name > _.name),
- future.get().topics.asScala.toList.sortWith(_.name > _.name)
- )
- }
-
- @ParameterizedTest
- @ApiKeyVersionsSource(apiKey = ApiKeys.OFFSET_COMMIT)
- def testCommitOffsets(version: Short): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val time = new MockTime()
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, time)
- val now = time.milliseconds()
-
- val ctx = makeContext(ApiKeys.OFFSET_COMMIT, version)
- val data = new OffsetCommitRequestData()
- .setGroupId("group")
- .setMemberId("member")
- .setGenerationIdOrMemberEpoch(10)
- .setRetentionTimeMs(1000)
- .setTopics(List(
- new OffsetCommitRequestData.OffsetCommitRequestTopic()
- .setName("foo")
- .setPartitions(List(
- new OffsetCommitRequestData.OffsetCommitRequestPartition()
- .setPartitionIndex(0)
- .setCommittedOffset(100)
- .setCommittedLeaderEpoch(1)
- ).asJava)
- ).asJava)
- val bufferSupplier = BufferSupplier.create()
-
- val future = adapter.commitOffsets(ctx, data, bufferSupplier)
- assertFalse(future.isDone)
-
- val capturedCallback: ArgumentCaptor[Map[TopicIdPartition, Errors] => Unit] =
- ArgumentCaptor.forClass(classOf[Map[TopicIdPartition, Errors] => Unit])
-
- verify(groupCoordinator).handleCommitOffsets(
- ArgumentMatchers.eq(data.groupId),
- ArgumentMatchers.eq(data.memberId),
- ArgumentMatchers.eq(None),
- ArgumentMatchers.eq(data.generationIdOrMemberEpoch),
- ArgumentMatchers.eq(Map(
- new TopicIdPartition(Uuid.ZERO_UUID, 0 , "foo") -> new OffsetAndMetadata(
- 100,
- OptionalInt.of(1),
- "",
- now,
- OptionalLong.of(now + 1000L)
- )
- )),
- capturedCallback.capture(),
- ArgumentMatchers.eq(new RequestLocal(bufferSupplier))
- )
-
- capturedCallback.getValue.apply(Map(
- new TopicIdPartition(Uuid.ZERO_UUID, 0 , "foo") -> Errors.NONE
- ))
-
- val expectedResponseData = new OffsetCommitResponseData()
- .setTopics(List(
- new OffsetCommitResponseData.OffsetCommitResponseTopic()
- .setName("foo")
- .setPartitions(List(
- new OffsetCommitResponseData.OffsetCommitResponsePartition()
- .setPartitionIndex(0)
- .setErrorCode(Errors.NONE.code)
- ).asJava)
- ).asJava)
-
- assertTrue(future.isDone)
- assertEquals(expectedResponseData, future.get())
- }
-
- @Test
- def testCommitTransactionalOffsets(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val time = new MockTime()
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, time)
- val now = time.milliseconds()
-
- val ctx = makeContext(ApiKeys.TXN_OFFSET_COMMIT, ApiKeys.TXN_OFFSET_COMMIT.latestVersion)
- val data = new TxnOffsetCommitRequestData()
- .setGroupId("group")
- .setMemberId("member")
- .setGenerationId(10)
- .setProducerEpoch(1)
- .setProducerId(2)
- .setTransactionalId("transaction-id")
- .setTopics(List(
- new TxnOffsetCommitRequestData.TxnOffsetCommitRequestTopic()
- .setName("foo")
- .setPartitions(List(
- new TxnOffsetCommitRequestData.TxnOffsetCommitRequestPartition()
- .setPartitionIndex(0)
- .setCommittedOffset(100)
- .setCommittedLeaderEpoch(1)
- ).asJava)
- ).asJava)
- val bufferSupplier = BufferSupplier.create()
-
- val future = adapter.commitTransactionalOffsets(ctx, data, bufferSupplier)
- assertFalse(future.isDone)
-
- val capturedCallback: ArgumentCaptor[Map[TopicIdPartition, Errors] => Unit] =
- ArgumentCaptor.forClass(classOf[Map[TopicIdPartition, Errors] => Unit])
-
- verify(groupCoordinator).handleTxnCommitOffsets(
- ArgumentMatchers.eq(data.groupId),
- ArgumentMatchers.eq(data.transactionalId),
- ArgumentMatchers.eq(data.producerId),
- ArgumentMatchers.eq(data.producerEpoch),
- ArgumentMatchers.eq(data.memberId),
- ArgumentMatchers.eq(None),
- ArgumentMatchers.eq(data.generationId),
- ArgumentMatchers.eq(Map(
- new TopicIdPartition(Uuid.ZERO_UUID, 0 , "foo") -> new OffsetAndMetadata(
- 100,
- OptionalInt.of(1),
- "",
- now,
- OptionalLong.empty()
- )
- )),
- capturedCallback.capture(),
- ArgumentMatchers.eq(new RequestLocal(bufferSupplier)),
- ArgumentMatchers.any()
- )
-
- capturedCallback.getValue.apply(Map(
- new TopicIdPartition(Uuid.ZERO_UUID, 0 , "foo") -> Errors.NONE
- ))
-
- val expectedData = new TxnOffsetCommitResponseData()
- .setTopics(List(
- new TxnOffsetCommitResponseData.TxnOffsetCommitResponseTopic()
- .setName("foo")
- .setPartitions(List(
- new TxnOffsetCommitResponseData.TxnOffsetCommitResponsePartition()
- .setPartitionIndex(0)
- .setErrorCode(Errors.NONE.code)
- ).asJava)
- ).asJava)
-
- assertTrue(future.isDone)
- assertEquals(expectedData, future.get())
- }
-
- def testDeleteOffsets(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- val foo0 = new TopicPartition("foo", 0)
- val foo1 = new TopicPartition("foo", 1)
- val bar0 = new TopicPartition("bar", 0)
- val bar1 = new TopicPartition("bar", 1)
-
- val ctx = makeContext(ApiKeys.OFFSET_DELETE, ApiKeys.OFFSET_DELETE.latestVersion)
- val data = new OffsetDeleteRequestData()
- .setGroupId("group")
- .setTopics(new OffsetDeleteRequestTopicCollection(List(
- new OffsetDeleteRequestTopic()
- .setName("foo")
- .setPartitions(List(
- new OffsetDeleteRequestPartition().setPartitionIndex(0),
- new OffsetDeleteRequestPartition().setPartitionIndex(1)
- ).asJava),
- new OffsetDeleteRequestTopic()
- .setName("bar")
- .setPartitions(List(
- new OffsetDeleteRequestPartition().setPartitionIndex(0),
- new OffsetDeleteRequestPartition().setPartitionIndex(1)
- ).asJava)
- ).asJava.iterator))
- val bufferSupplier = BufferSupplier.create()
-
- when(groupCoordinator.handleDeleteOffsets(
- data.groupId,
- Seq(foo0, foo1, bar0, bar1),
- new RequestLocal(bufferSupplier)
- )).thenReturn((
- Errors.NONE,
- Map(
- foo0 -> Errors.NONE,
- foo1 -> Errors.NONE,
- bar0 -> Errors.GROUP_SUBSCRIBED_TO_TOPIC,
- bar1 -> Errors.GROUP_SUBSCRIBED_TO_TOPIC,
- )
- ))
-
- val future = adapter.deleteOffsets(ctx, data, bufferSupplier)
-
- val expectedData = new OffsetDeleteResponseData()
- .setTopics(new OffsetDeleteResponseTopicCollection(List(
- new OffsetDeleteResponseTopic()
- .setName("foo")
- .setPartitions(new OffsetDeleteResponsePartitionCollection(List(
- new OffsetDeleteResponsePartition()
- .setPartitionIndex(0)
- .setErrorCode(Errors.NONE.code),
- new OffsetDeleteResponsePartition()
- .setPartitionIndex(1)
- .setErrorCode(Errors.NONE.code)
- ).asJava.iterator)),
- new OffsetDeleteResponseTopic()
- .setName("bar")
- .setPartitions(new OffsetDeleteResponsePartitionCollection(List(
- new OffsetDeleteResponsePartition()
- .setPartitionIndex(0)
- .setErrorCode(Errors.GROUP_SUBSCRIBED_TO_TOPIC.code),
- new OffsetDeleteResponsePartition()
- .setPartitionIndex(1)
- .setErrorCode(Errors.GROUP_SUBSCRIBED_TO_TOPIC.code)
- ).asJava.iterator)),
- ).asJava.iterator))
-
- assertTrue(future.isDone)
- assertEquals(expectedData, future.get())
- }
-
- @Test
- def testDeleteOffsetsWithGroupLevelError(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- val foo0 = new TopicPartition("foo", 0)
- val foo1 = new TopicPartition("foo", 1)
-
- val ctx = makeContext(ApiKeys.OFFSET_DELETE, ApiKeys.OFFSET_DELETE.latestVersion)
- val data = new OffsetDeleteRequestData()
- .setGroupId("group")
- .setTopics(new OffsetDeleteRequestTopicCollection(List(
- new OffsetDeleteRequestTopic()
- .setName("foo")
- .setPartitions(List(
- new OffsetDeleteRequestPartition().setPartitionIndex(0),
- new OffsetDeleteRequestPartition().setPartitionIndex(1)
- ).asJava)
- ).asJava.iterator))
- val bufferSupplier = BufferSupplier.create()
-
- when(groupCoordinator.handleDeleteOffsets(
- data.groupId,
- Seq(foo0, foo1),
- new RequestLocal(bufferSupplier)
- )).thenReturn((Errors.INVALID_GROUP_ID, Map.empty[TopicPartition, Errors]))
-
- val future = adapter.deleteOffsets(ctx, data, bufferSupplier)
- assertTrue(future.isDone)
- assertTrue(future.isCompletedExceptionally)
- assertFutureThrows(classOf[InvalidGroupIdException], future)
- }
-
- @Test
- def testConsumerGroupDescribe(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
- val context = makeContext(ApiKeys.CONSUMER_GROUP_DESCRIBE, ApiKeys.CONSUMER_GROUP_DESCRIBE.latestVersion)
- val groupIds = List("group-id-1", "group-id-2").asJava
-
- val future = adapter.consumerGroupDescribe(context, groupIds)
- assertTrue(future.isDone)
- assertTrue(future.isCompletedExceptionally)
- assertFutureThrows(classOf[UnsupportedVersionException], future)
- }
-
- @Test
- def testShareGroupDescribe(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
- val context = makeContext(ApiKeys.SHARE_GROUP_DESCRIBE, ApiKeys.SHARE_GROUP_DESCRIBE.latestVersion)
- val groupIds = List("group-id-1", "group-id-2").asJava
-
- val future = adapter.shareGroupDescribe(context, groupIds)
- assertTrue(future.isDone)
- assertTrue(future.isCompletedExceptionally)
- assertFutureThrows(classOf[UnsupportedVersionException], future)
- }
-
- @Test
- def testOnTransactionCompletedWithUnexpectedException(): Unit = {
- val groupCoordinator = mock(classOf[GroupCoordinator])
- val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
- when(groupCoordinator.scheduleHandleTxnCompletion(
- any(),
- any(),
- any()
- )).thenThrow(new IllegalStateException("Oh no!"))
-
- val future = adapter.onTransactionCompleted(
- 10,
- Seq.empty[TopicPartition].asJava,
- TransactionResult.COMMIT
- )
-
- assertTrue(future.isDone)
- assertTrue(future.isCompletedExceptionally)
- assertFutureThrows(classOf[IllegalStateException], future)
- }
-}
diff --git a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorConcurrencyTest.scala b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorConcurrencyTest.scala
deleted file mode 100644
index 3eecdfe65e1..00000000000
--- a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorConcurrencyTest.scala
+++ /dev/null
@@ -1,406 +0,0 @@
-/**
- * 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 kafka.coordinator.group
-
-import java.util.{OptionalInt, OptionalLong, Properties}
-import java.util.concurrent.locks.{Lock, ReentrantLock}
-import java.util.concurrent.{ConcurrentHashMap, TimeUnit}
-import kafka.coordinator.AbstractCoordinatorConcurrencyTest
-import kafka.coordinator.AbstractCoordinatorConcurrencyTest._
-import kafka.coordinator.group.GroupCoordinatorConcurrencyTest._
-import kafka.server.{KafkaConfig, KafkaRequestHandler}
-import kafka.utils.CoreUtils
-import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
-import org.apache.kafka.common.internals.Topic
-import org.apache.kafka.common.metrics.Metrics
-import org.apache.kafka.common.message.LeaveGroupRequestData.MemberIdentity
-import org.apache.kafka.common.protocol.{ApiKeys, Errors}
-import org.apache.kafka.common.requests.{JoinGroupRequest, OffsetFetchResponse}
-import org.apache.kafka.common.utils.{Time, Utils}
-import org.apache.kafka.coordinator.group.{GroupCoordinatorConfig, OffsetAndMetadata}
-import org.apache.kafka.server.common.RequestLocal
-import org.apache.kafka.server.purgatory.DelayedOperationPurgatory
-import org.junit.jupiter.api.Assertions._
-import org.junit.jupiter.api.{AfterEach, BeforeEach, Test}
-
-import scala.collection._
-import scala.concurrent.duration.Duration
-import scala.concurrent.{Await, Future, Promise, TimeoutException}
-
-class GroupCoordinatorConcurrencyTest extends AbstractCoordinatorConcurrencyTest[GroupMember] {
-
- private val protocolType = "consumer"
- private val protocolName = "range"
- private val metadata = Array[Byte]()
- private val protocols = List((protocolName, metadata))
- private val nGroups = nThreads * 10
- private val nMembersPerGroup = nThreads * 5
- private val numPartitions = 2
- private var metrics: Metrics = _
-
- private val allOperations = Seq(
- new JoinGroupOperation,
- new SyncGroupOperation,
- new OffsetFetchOperation,
- new CommitOffsetsOperation,
- new HeartbeatOperation,
- new LeaveGroupOperation
- )
-
- var heartbeatPurgatory: DelayedOperationPurgatory[DelayedHeartbeat] = _
- var rebalancePurgatory: DelayedOperationPurgatory[DelayedRebalance] = _
- var groupCoordinator: GroupCoordinator = _
-
- @BeforeEach
- override def setUp(): Unit = {
- super.setUp()
-
- serverProps.setProperty(GroupCoordinatorConfig.GROUP_MIN_SESSION_TIMEOUT_MS_CONFIG, ConsumerMinSessionTimeout.toString)
- serverProps.setProperty(GroupCoordinatorConfig.GROUP_MAX_SESSION_TIMEOUT_MS_CONFIG, ConsumerMaxSessionTimeout.toString)
- serverProps.setProperty(GroupCoordinatorConfig.GROUP_INITIAL_REBALANCE_DELAY_MS_CONFIG, GroupInitialRebalanceDelay.toString)
-
- val config = KafkaConfig.fromProps(serverProps)
-
- heartbeatPurgatory = new DelayedOperationPurgatory[DelayedHeartbeat]("Heartbeat", timer, config.brokerId, 1000, false, true)
- rebalancePurgatory = new DelayedOperationPurgatory[DelayedRebalance]("Rebalance", timer, config.brokerId, 1000, false, true)
-
- metrics = new Metrics
- groupCoordinator = GroupCoordinator(config, replicaManager, heartbeatPurgatory, rebalancePurgatory, timer.time, metrics)
- groupCoordinator.startup(() => numPartitions, enableMetadataExpiration = false)
-
- // Transactional appends attempt to schedule to the request handler thread using
- // a non request handler thread. Set this to avoid error.
- KafkaRequestHandler.setBypassThreadCheck(true)
- }
-
- @AfterEach
- override def tearDown(): Unit = {
- try {
- CoreUtils.swallow(groupCoordinator.shutdown(), this)
- Utils.closeQuietly(metrics, "metrics")
- } finally {
- super.tearDown()
- }
- }
-
- def createGroupMembers(groupPrefix: String): Set[GroupMember] = {
- (0 until nGroups).flatMap { i =>
- new Group(s"$groupPrefix$i", nMembersPerGroup, groupCoordinator).members
- }.toSet
- }
-
- @Test
- def testConcurrentGoodPathSequence(): Unit = {
- verifyConcurrentOperations(createGroupMembers, allOperations)
- }
-
- @Test
- def testConcurrentTxnGoodPathSequence(): Unit = {
- verifyConcurrentOperations(createGroupMembers, Seq(
- new JoinGroupOperation,
- new SyncGroupOperation,
- new OffsetFetchOperation,
- new CommitTxnOffsetsOperation,
- new CompleteTxnOperation,
- new HeartbeatOperation,
- new LeaveGroupOperation
- ))
- }
-
- @Test
- def testConcurrentRandomSequence(): Unit = {
- /**
- * handleTxnCommitOffsets does not complete delayed requests now so it causes error if handleTxnCompletion is executed
- * before completing delayed request. In random mode, we use this global lock to prevent such an error.
- */
- val lock = new ReentrantLock()
- verifyConcurrentRandomSequences(createGroupMembers, Seq(
- new JoinGroupOperation,
- new SyncGroupOperation,
- new OffsetFetchOperation,
- new CommitTxnOffsetsOperation(lock = Some(lock)),
- new CompleteTxnOperation(lock = Some(lock)),
- new HeartbeatOperation,
- new LeaveGroupOperation
- ))
- }
-
- @Test
- def testConcurrentJoinGroupEnforceGroupMaxSize(): Unit = {
- val groupMaxSize = 1
- val newProperties = new Properties
- newProperties.put(GroupCoordinatorConfig.GROUP_MAX_SIZE_CONFIG, groupMaxSize.toString)
- val config = KafkaConfig.fromProps(serverProps, newProperties)
-
- if (groupCoordinator != null)
- groupCoordinator.shutdown()
- groupCoordinator = GroupCoordinator(config, replicaManager, heartbeatPurgatory,
- rebalancePurgatory, timer.time, new Metrics())
- groupCoordinator.startup(() => numPartitions, enableMetadataExpiration = false)
-
- val members = new Group(s"group", nMembersPerGroup, groupCoordinator)
- .members
- val joinOp = new JoinGroupOperation()
-
- verifyConcurrentActions(members.toSet.map(joinOp.actionNoVerify))
-
- val errors = members.map { member =>
- val joinGroupResult = joinOp.await(member, DefaultRebalanceTimeout)
- joinGroupResult.error
- }
-
- assertEquals(groupMaxSize, errors.count(_ == Errors.NONE))
- assertEquals(members.size-groupMaxSize, errors.count(_ == Errors.GROUP_MAX_SIZE_REACHED))
- }
-
- abstract class GroupOperation[R, C] extends Operation {
- val responseFutures = new ConcurrentHashMap[GroupMember, Future[R]]()
-
- def setUpCallback(member: GroupMember): C = {
- val responsePromise = Promise[R]()
- val responseFuture = responsePromise.future
- responseFutures.put(member, responseFuture)
- responseCallback(responsePromise)
- }
- def responseCallback(responsePromise: Promise[R]): C
-
- override def run(member: GroupMember): Unit = {
- val responseCallback = setUpCallback(member)
- runWithCallback(member, responseCallback)
- }
-
- def runWithCallback(member: GroupMember, responseCallback: C): Unit
-
- def await(member: GroupMember, timeoutMs: Long): R = {
- var retries = (timeoutMs + 10) / 10
- val responseFuture = responseFutures.get(member)
- while (retries > 0) {
- timer.advanceClock(10)
- try {
- return Await.result(responseFuture, Duration(10, TimeUnit.MILLISECONDS))
- } catch {
- case _: TimeoutException =>
- }
- retries -= 1
- }
- throw new TimeoutException(s"Operation did not complete within $timeoutMs millis")
- }
- }
-
- class JoinGroupOperation extends GroupOperation[JoinGroupCallbackParams, JoinGroupCallback] {
- override def responseCallback(responsePromise: Promise[JoinGroupCallbackParams]): JoinGroupCallback = {
- val callback: JoinGroupCallback = responsePromise.success
- callback
- }
- override def runWithCallback(member: GroupMember, responseCallback: JoinGroupCallback): Unit = {
- groupCoordinator.handleJoinGroup(member.groupId, member.memberId, None, requireKnownMemberId = false,
- supportSkippingAssignment = false, "clientId", "clientHost", DefaultRebalanceTimeout,
- DefaultSessionTimeout, protocolType, protocols, responseCallback)
- replicaManager.tryCompleteActions()
- }
- override def awaitAndVerify(member: GroupMember): Unit = {
- val joinGroupResult = await(member, DefaultRebalanceTimeout)
- assertEquals(Errors.NONE, joinGroupResult.error)
- member.memberId = joinGroupResult.memberId
- member.generationId = joinGroupResult.generationId
- }
- }
-
- class SyncGroupOperation extends GroupOperation[SyncGroupCallbackParams, SyncGroupCallback] {
- override def responseCallback(responsePromise: Promise[SyncGroupCallbackParams]): SyncGroupCallback = {
- val callback: SyncGroupCallback = syncGroupResult =>
- responsePromise.success(syncGroupResult.error, syncGroupResult.memberAssignment)
- callback
- }
- override def runWithCallback(member: GroupMember, responseCallback: SyncGroupCallback): Unit = {
- if (member.leader) {
- groupCoordinator.handleSyncGroup(member.groupId, member.generationId, member.memberId,
- Some(protocolType), Some(protocolName), member.groupInstanceId, member.group.assignment, responseCallback)
- } else {
- groupCoordinator.handleSyncGroup(member.groupId, member.generationId, member.memberId,
- Some(protocolType), Some(protocolName), member.groupInstanceId, Map.empty[String, Array[Byte]], responseCallback)
- }
- replicaManager.tryCompleteActions()
- }
- override def awaitAndVerify(member: GroupMember): Unit = {
- val result = await(member, DefaultSessionTimeout)
- assertEquals(Errors.NONE, result._1)
- assertNotNull(result._2)
- assertEquals(0, result._2.length)
- }
- }
-
- class HeartbeatOperation extends GroupOperation[HeartbeatCallbackParams, HeartbeatCallback] {
- override def responseCallback(responsePromise: Promise[HeartbeatCallbackParams]): HeartbeatCallback = {
- val callback: HeartbeatCallback = error => responsePromise.success(error)
- callback
- }
- override def runWithCallback(member: GroupMember, responseCallback: HeartbeatCallback): Unit = {
- groupCoordinator.handleHeartbeat(member.groupId, member.memberId,
- member.groupInstanceId, member.generationId, responseCallback)
- replicaManager.tryCompleteActions()
- }
- override def awaitAndVerify(member: GroupMember): Unit = {
- val error = await(member, DefaultSessionTimeout)
- assertEquals(Errors.NONE, error)
- }
- }
-
- class OffsetFetchOperation extends GroupOperation[OffsetFetchCallbackParams, OffsetFetchCallback] {
- override def responseCallback(responsePromise: Promise[OffsetFetchCallbackParams]): OffsetFetchCallback = {
- val callback: OffsetFetchCallback = (error, offsets) => responsePromise.success(error, offsets)
- callback
- }
- override def runWithCallback(member: GroupMember, responseCallback: OffsetFetchCallback): Unit = {
- val (error, partitionData) = groupCoordinator.handleFetchOffsets(member.groupId, requireStable = true, None)
- replicaManager.tryCompleteActions()
- responseCallback(error, partitionData)
- }
- override def awaitAndVerify(member: GroupMember): Unit = {
- val result = await(member, 500)
- assertEquals(Errors.NONE, result._1)
- assertEquals(Map.empty, result._2)
- }
- }
-
- class CommitOffsetsOperation extends GroupOperation[CommitOffsetCallbackParams, CommitOffsetCallback] {
- override def responseCallback(responsePromise: Promise[CommitOffsetCallbackParams]): CommitOffsetCallback = {
- val callback: CommitOffsetCallback = offsets => responsePromise.success(offsets)
- callback
- }
- override def runWithCallback(member: GroupMember, responseCallback: CommitOffsetCallback): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offsets = immutable.Map(tip -> new OffsetAndMetadata(1, OptionalInt.empty(), "", Time.SYSTEM.milliseconds(), OptionalLong.empty()))
- groupCoordinator.handleCommitOffsets(member.groupId, member.memberId,
- member.groupInstanceId, member.generationId, offsets, responseCallback)
- replicaManager.tryCompleteActions()
- }
- override def awaitAndVerify(member: GroupMember): Unit = {
- val offsets = await(member, 500)
- offsets.foreach { case (_, error) => assertEquals(Errors.NONE, error) }
- }
- }
-
- class CommitTxnOffsetsOperation(lock: Option[Lock] = None) extends CommitOffsetsOperation {
- override def runWithCallback(member: GroupMember, responseCallback: CommitOffsetCallback): Unit = {
- val offsets = immutable.Map(new TopicIdPartition(Uuid.randomUuid(), 0, "topic") -> new OffsetAndMetadata(1, OptionalInt.empty(), "", Time.SYSTEM.milliseconds(), OptionalLong.empty()))
- val producerId = 1000L
- val producerEpoch : Short = 2
- // When transaction offsets are appended to the log, transactions may be scheduled for
- // completion. Since group metadata locks are acquired for transaction completion, include
- // this in the callback to test that there are no deadlocks.
- def callbackWithTxnCompletion(errors: Map[TopicIdPartition, Errors]): Unit = {
- val offsetsPartitions = (0 to numPartitions).map(new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, _))
- groupCoordinator.groupManager.scheduleHandleTxnCompletion(producerId,
- offsetsPartitions.map(_.partition).toSet, isCommit = random.nextBoolean)
- responseCallback(errors)
- }
- lock.foreach(_.lock())
- try {
- // Since the replica manager is mocked we can use a dummy value for transactionalId.
- groupCoordinator.handleTxnCommitOffsets(member.group.groupId, "dummy-txn-id", producerId, producerEpoch,
- JoinGroupRequest.UNKNOWN_MEMBER_ID, Option.empty, JoinGroupRequest.UNKNOWN_GENERATION_ID,
- offsets, callbackWithTxnCompletion, RequestLocal.noCaching, ApiKeys.TXN_OFFSET_COMMIT.latestVersion())
- replicaManager.tryCompleteActions()
- } finally lock.foreach(_.unlock())
- }
- }
-
- class CompleteTxnOperation(lock: Option[Lock] = None) extends GroupOperation[CompleteTxnCallbackParams, CompleteTxnCallback] {
- override def responseCallback(responsePromise: Promise[CompleteTxnCallbackParams]): CompleteTxnCallback = {
- val callback: CompleteTxnCallback = error => responsePromise.success(error)
- callback
- }
- override def runWithCallback(member: GroupMember, responseCallback: CompleteTxnCallback): Unit = {
- val producerId = 1000L
- val offsetsPartitions = (0 to numPartitions).map(new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, _))
- lock.foreach(_.lock())
- try {
- groupCoordinator.groupManager.handleTxnCompletion(producerId,
- offsetsPartitions.map(_.partition).toSet, isCommit = random.nextBoolean)
- responseCallback(Errors.NONE)
- } finally lock.foreach(_.unlock())
-
- }
- override def awaitAndVerify(member: GroupMember): Unit = {
- val error = await(member, 500)
- assertEquals(Errors.NONE, error)
- }
- }
-
- class LeaveGroupOperation extends GroupOperation[LeaveGroupCallbackParams, LeaveGroupCallback] {
- override def responseCallback(responsePromise: Promise[LeaveGroupCallbackParams]): LeaveGroupCallback = {
- val callback: LeaveGroupCallback = result => responsePromise.success(result)
- callback
- }
- override def runWithCallback(member: GroupMember, responseCallback: LeaveGroupCallback): Unit = {
- val memberIdentity = new MemberIdentity()
- .setMemberId(member.memberId)
- groupCoordinator.handleLeaveGroup(member.group.groupId, List(memberIdentity), responseCallback)
- }
- override def awaitAndVerify(member: GroupMember): Unit = {
- val leaveGroupResult = await(member, DefaultSessionTimeout)
-
- val memberResponses = leaveGroupResult.memberResponses
- GroupCoordinatorTest.verifyLeaveGroupResult(leaveGroupResult, Errors.NONE, List(Errors.NONE))
- assertEquals(member.memberId, memberResponses.head.memberId)
- assertEquals(None, memberResponses.head.groupInstanceId)
- }
- }
-}
-
-object GroupCoordinatorConcurrencyTest {
-
- type JoinGroupCallbackParams = JoinGroupResult
- type JoinGroupCallback = JoinGroupResult => Unit
- type SyncGroupCallbackParams = (Errors, Array[Byte])
- type SyncGroupCallback = SyncGroupResult => Unit
- type HeartbeatCallbackParams = Errors
- type HeartbeatCallback = Errors => Unit
- type OffsetFetchCallbackParams = (Errors, Map[TopicPartition, OffsetFetchResponse.PartitionData])
- type OffsetFetchCallback = (Errors, Map[TopicPartition, OffsetFetchResponse.PartitionData]) => Unit
- type CommitOffsetCallbackParams = Map[TopicIdPartition, Errors]
- type CommitOffsetCallback = Map[TopicIdPartition, Errors] => Unit
- type LeaveGroupCallbackParams = LeaveGroupResult
- type LeaveGroupCallback = LeaveGroupResult => Unit
- type CompleteTxnCallbackParams = Errors
- type CompleteTxnCallback = Errors => Unit
-
- private val ConsumerMinSessionTimeout = 10
- private val ConsumerMaxSessionTimeout = 120 * 1000
- private val DefaultRebalanceTimeout = 60 * 1000
- private val DefaultSessionTimeout = 60 * 1000
- private val GroupInitialRebalanceDelay = 50
-
- class Group(val groupId: String, nMembers: Int, groupCoordinator: GroupCoordinator) {
- val groupPartitionId: Int = groupCoordinator.partitionFor(groupId)
- groupCoordinator.groupManager.addOwnedPartition(groupPartitionId)
- val members: Seq[GroupMember] = (0 until nMembers).map { i =>
- new GroupMember(this, groupPartitionId, i == 0)
- }
- def assignment: Map[String, Array[Byte]] = members.map { m => (m.memberId, Array[Byte]()) }.toMap
- }
-
- class GroupMember(val group: Group, val groupPartitionId: Int, val leader: Boolean) extends CoordinatorMember {
- @volatile var memberId: String = JoinGroupRequest.UNKNOWN_MEMBER_ID
- @volatile var groupInstanceId: Option[String] = None
- @volatile var generationId: Int = -1
- def groupId: String = group.groupId
- }
-
-}
diff --git a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorTest.scala b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorTest.scala
deleted file mode 100644
index 19cbb382f7c..00000000000
--- a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorTest.scala
+++ /dev/null
@@ -1,4249 +0,0 @@
-/**
- * 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 kafka.coordinator.group
-
-import java.util.{OptionalInt, OptionalLong}
-import kafka.server.{HostedPartition, KafkaConfig, KafkaRequestHandler, ReplicaManager}
-import kafka.utils._
-import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
-import org.apache.kafka.common.protocol.{ApiKeys, Errors}
-import org.apache.kafka.common.record.{MemoryRecords, RecordBatch}
-import org.apache.kafka.common.requests.ProduceResponse.PartitionResponse
-import org.apache.kafka.common.requests.{JoinGroupRequest, OffsetCommitRequest, OffsetFetchResponse, TransactionResult}
-
-import java.util.concurrent.TimeUnit
-import java.util.concurrent.locks.ReentrantLock
-import kafka.cluster.Partition
-import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor.Subscription
-import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
-import org.apache.kafka.common.internals.Topic
-import org.apache.kafka.common.metrics.Metrics
-import org.apache.kafka.common.message.LeaveGroupRequestData.MemberIdentity
-import org.apache.kafka.coordinator.group.{GroupCoordinatorConfig, OffsetAndMetadata}
-import org.apache.kafka.server.ActionQueue
-import org.apache.kafka.server.common.RequestLocal
-import org.apache.kafka.server.purgatory.DelayedOperationPurgatory
-import org.apache.kafka.server.util.timer.MockTimer
-import org.apache.kafka.server.util.{KafkaScheduler, MockTime}
-import org.apache.kafka.storage.internals.log.{AppendOrigin, VerificationGuard}
-import org.junit.jupiter.api.Assertions._
-import org.junit.jupiter.api.{AfterEach, BeforeEach, Test}
-import org.junit.jupiter.params.ParameterizedTest
-import org.junit.jupiter.params.provider.ValueSource
-import org.mockito.{ArgumentCaptor, ArgumentMatchers}
-import org.mockito.ArgumentMatchers.{any, anyLong, anyShort}
-import org.mockito.Mockito.{mock, when}
-
-import scala.jdk.CollectionConverters._
-import scala.collection.{Seq, mutable}
-import scala.collection.mutable.ArrayBuffer
-import scala.concurrent.duration.Duration
-import scala.concurrent.{Await, Future, Promise, TimeoutException}
-
-class GroupCoordinatorTest {
- import GroupCoordinatorTest._
-
- type JoinGroupCallback = JoinGroupResult => Unit
- type SyncGroupCallback = SyncGroupResult => Unit
- type HeartbeatCallbackParams = Errors
- type HeartbeatCallback = Errors => Unit
- type CommitOffsetCallbackParams = Map[TopicIdPartition, Errors]
- type CommitOffsetCallback = Map[TopicIdPartition, Errors] => Unit
- type LeaveGroupCallback = LeaveGroupResult => Unit
-
- val ClientId = "consumer-test"
- val ClientHost = "localhost"
- val GroupMinSessionTimeout = 10
- val GroupMaxSessionTimeout = 10 * 60 * 1000
- val GroupMaxSize = 4
- val DefaultRebalanceTimeout = 500
- val DefaultSessionTimeout = 500
- val GroupInitialRebalanceDelay = 50
- var timer: MockTimer = _
- var groupCoordinator: GroupCoordinator = _
- var replicaManager: ReplicaManager = _
- var scheduler: KafkaScheduler = _
-
- private val groupId = "groupId"
- private val protocolType = "consumer"
- private val protocolName = "range"
- private val memberId = "memberId"
- private val groupInstanceId = "groupInstanceId"
- private val leaderInstanceId = "leader"
- private val followerInstanceId = "follower"
- private val invalidMemberId = "invalidMember"
- private val metadata = Array[Byte]()
- private val protocols = List((protocolName, metadata))
- private val protocolSuperset = List((protocolName, metadata), ("roundrobin", metadata))
- private val requireStable = true
- private var groupPartitionId: Int = -1
-
- // we use this string value since its hashcode % #.partitions is different
- private val otherGroupId = "otherGroup"
-
- @BeforeEach
- def setUp(): Unit = {
- val props = TestUtils.createBrokerConfig(0)
- props.setProperty(GroupCoordinatorConfig.GROUP_MIN_SESSION_TIMEOUT_MS_CONFIG, GroupMinSessionTimeout.toString)
- props.setProperty(GroupCoordinatorConfig.GROUP_MAX_SESSION_TIMEOUT_MS_CONFIG, GroupMaxSessionTimeout.toString)
- props.setProperty(GroupCoordinatorConfig.GROUP_MAX_SIZE_CONFIG, GroupMaxSize.toString)
- props.setProperty(GroupCoordinatorConfig.GROUP_INITIAL_REBALANCE_DELAY_MS_CONFIG, GroupInitialRebalanceDelay.toString)
- // make two partitions of the group topic to make sure some partitions are not owned by the coordinator
- val ret = mutable.Map[String, Map[Int, Seq[Int]]]()
- ret += (Topic.GROUP_METADATA_TOPIC_NAME -> Map(0 -> Seq(1), 1 -> Seq(1)))
-
- replicaManager = mock(classOf[ReplicaManager])
-
- timer = new MockTimer
-
- val config = KafkaConfig.fromProps(props)
-
- val heartbeatPurgatory = new DelayedOperationPurgatory[DelayedHeartbeat]("Heartbeat", timer, 1000, config.brokerId, false, true)
- val rebalancePurgatory = new DelayedOperationPurgatory[DelayedRebalance]("Rebalance", timer, 1000, config.brokerId, false, true)
-
- groupCoordinator = GroupCoordinator(config, replicaManager, heartbeatPurgatory, rebalancePurgatory, timer.time, new Metrics())
- // make two partitions of the group topic to make sure some partitions are not owned by the coordinator
- groupCoordinator.startup(() => 2, enableMetadataExpiration = false)
-
- // add the partition into the owned partition list
- groupPartitionId = groupCoordinator.partitionFor(groupId)
- groupCoordinator.groupManager.addOwnedPartition(groupPartitionId)
- }
-
- @AfterEach
- def tearDown(): Unit = {
- if (groupCoordinator != null)
- groupCoordinator.shutdown()
- }
-
- @Test
- def testRequestHandlingWhileLoadingInProgress(): Unit = {
- val otherGroupPartitionId = groupCoordinator.groupManager.partitionFor(otherGroupId)
- assertTrue(otherGroupPartitionId != groupPartitionId)
-
- groupCoordinator.groupManager.addLoadingPartition(otherGroupPartitionId)
- assertTrue(groupCoordinator.groupManager.isGroupLoading(otherGroupId))
-
- // Dynamic Member JoinGroup
- var joinGroupResponse: Option[JoinGroupResult] = None
- groupCoordinator.handleJoinGroup(otherGroupId, memberId, None, requireKnownMemberId = true, supportSkippingAssignment = true, "clientId", "clientHost", 60000, 10000, "consumer",
- List("range" -> new Array[Byte](0)), result => { joinGroupResponse = Some(result)})
- assertEquals(Some(Errors.COORDINATOR_LOAD_IN_PROGRESS), joinGroupResponse.map(_.error))
-
- // Static Member JoinGroup
- groupCoordinator.handleJoinGroup(otherGroupId, memberId, Some("groupInstanceId"), requireKnownMemberId = false, supportSkippingAssignment = true, "clientId", "clientHost", 60000, 10000, "consumer",
- List("range" -> new Array[Byte](0)), result => { joinGroupResponse = Some(result)})
- assertEquals(Some(Errors.COORDINATOR_LOAD_IN_PROGRESS), joinGroupResponse.map(_.error))
-
- // SyncGroup
- var syncGroupResponse: Option[Errors] = None
- groupCoordinator.handleSyncGroup(otherGroupId, 1, memberId, Some("consumer"), Some("range"), None, Map.empty[String, Array[Byte]],
- syncGroupResult => syncGroupResponse = Some(syncGroupResult.error))
- assertEquals(Some(Errors.REBALANCE_IN_PROGRESS), syncGroupResponse)
-
- // OffsetCommit
- val topicIdPartition = new TopicIdPartition(Uuid.randomUuid(), 0 , "foo")
- var offsetCommitErrors = Map.empty[TopicIdPartition, Errors]
- groupCoordinator.handleCommitOffsets(otherGroupId, memberId, None, 1,
- Map(topicIdPartition -> offsetAndMetadata(15L)), result => { offsetCommitErrors = result })
- assertEquals(Map(topicIdPartition -> Errors.COORDINATOR_LOAD_IN_PROGRESS), offsetCommitErrors)
-
- // Heartbeat
- var heartbeatError: Option[Errors] = None
- groupCoordinator.handleHeartbeat(otherGroupId, memberId, None, 1, error => { heartbeatError = Some(error) })
- assertEquals(Some(Errors.NONE), heartbeatError)
-
- // DescribeGroups
- val (describeGroupError, _, _) = groupCoordinator.handleDescribeGroup(otherGroupId, ApiKeys.DESCRIBE_GROUPS.latestVersion)
- assertEquals(Errors.COORDINATOR_LOAD_IN_PROGRESS, describeGroupError)
-
- // ListGroups
- val (listGroupsError, _) = groupCoordinator.handleListGroups(Set(), Set())
- assertEquals(Errors.COORDINATOR_LOAD_IN_PROGRESS, listGroupsError)
-
- // DeleteGroups
- val deleteGroupsErrors = groupCoordinator.handleDeleteGroups(Set(otherGroupId))
- assertEquals(Some(Errors.COORDINATOR_LOAD_IN_PROGRESS), deleteGroupsErrors.get(otherGroupId))
-
- // Check that non-loading groups are still accessible
- assertEquals(Errors.GROUP_ID_NOT_FOUND, groupCoordinator.handleDescribeGroup(groupId, ApiKeys.DESCRIBE_GROUPS.latestVersion)._1)
-
- // After loading, we should be able to access the group
- val otherGroupMetadataTopicPartition = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, otherGroupPartitionId)
- when(replicaManager.getLog(otherGroupMetadataTopicPartition)).thenReturn(None)
-
- // Call removeGroupsAndOffsets so that partition removed from loadingPartitions
- groupCoordinator.groupManager.removeGroupsAndOffsets(otherGroupMetadataTopicPartition, OptionalInt.of(1), group => {})
- groupCoordinator.groupManager.loadGroupsAndOffsets(otherGroupMetadataTopicPartition, 1, group => {}, 0L)
- assertEquals(Errors.GROUP_ID_NOT_FOUND, groupCoordinator.handleDescribeGroup(otherGroupId, ApiKeys.DESCRIBE_GROUPS.latestVersion)._1)
- }
-
- @Test
- def testOffsetsRetentionMsIntegerOverflow(): Unit = {
- val props = TestUtils.createBrokerConfig(0)
- props.setProperty(GroupCoordinatorConfig.OFFSETS_RETENTION_MINUTES_CONFIG, Integer.MAX_VALUE.toString)
- val config = KafkaConfig.fromProps(props)
- val offsetConfig = GroupCoordinator.offsetConfig(config)
- assertEquals(offsetConfig.offsetsRetentionMs, Integer.MAX_VALUE * 60L * 1000L)
- }
-
- @Test
- def testJoinGroupWrongCoordinator(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- var joinGroupResult = dynamicJoinGroup(otherGroupId, memberId, protocolType, protocols)
- assertEquals(Errors.NOT_COORDINATOR, joinGroupResult.error)
-
- joinGroupResult = staticJoinGroup(otherGroupId, memberId, groupInstanceId, protocolType, protocols)
- assertEquals(Errors.NOT_COORDINATOR, joinGroupResult.error)
- }
-
- @Test
- def testJoinGroupShouldReceiveErrorIfGroupOverMaxSize(): Unit = {
- val futures = ArrayBuffer[Future[JoinGroupResult]]()
- val rebalanceTimeout = GroupInitialRebalanceDelay * 2
-
- for (i <- 1.to(GroupMaxSize)) {
- futures += sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols, rebalanceTimeout = rebalanceTimeout)
- if (i != 1)
- timer.advanceClock(GroupInitialRebalanceDelay)
- }
- // advance clock beyond rebalanceTimeout
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
- for (future <- futures) {
- assertEquals(Errors.NONE, await(future, 1).error)
- }
-
- // Should receive an error since the group is full
- val errorFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols, rebalanceTimeout = rebalanceTimeout)
- assertEquals(Errors.GROUP_MAX_SIZE_REACHED, await(errorFuture, 1).error)
- }
-
- @Test
- def testDynamicMembersJoinGroupWithMaxSizeAndRequiredKnownMember(): Unit = {
- val requiredKnownMemberId = true
- val nbMembers = GroupMaxSize + 1
-
- // First JoinRequests
- var futures = 1.to(nbMembers).map { _ =>
- sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols,
- None, DefaultSessionTimeout, DefaultRebalanceTimeout, requiredKnownMemberId)
- }
-
- // Get back the assigned member ids
- val memberIds = futures.map(await(_, 1).memberId)
-
- // Second JoinRequests
- futures = memberIds.map { memberId =>
- sendJoinGroup(groupId, memberId, protocolType, protocols,
- None, DefaultSessionTimeout, DefaultRebalanceTimeout, requiredKnownMemberId)
- }
-
- // advance clock by GroupInitialRebalanceDelay to complete first InitialDelayedJoin
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
- // advance clock by GroupInitialRebalanceDelay to complete second InitialDelayedJoin
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
-
- // Awaiting results
- val errors = futures.map(await(_, DefaultRebalanceTimeout + 1).error)
-
- assertEquals(GroupMaxSize, errors.count(_ == Errors.NONE))
- assertEquals(nbMembers-GroupMaxSize, errors.count(_ == Errors.GROUP_MAX_SIZE_REACHED))
-
- // Members which were accepted can rejoin, others are rejected, while
- // completing rebalance
- futures = memberIds.map { memberId =>
- sendJoinGroup(groupId, memberId, protocolType, protocols,
- None, DefaultSessionTimeout, DefaultRebalanceTimeout, requiredKnownMemberId)
- }
-
- // Awaiting results
- val rejoinErrors = futures.map(await(_, 1).error)
-
- assertEquals(errors, rejoinErrors)
- }
-
- @Test
- def testDynamicMembersJoinGroupWithMaxSize(): Unit = {
- val requiredKnownMemberId = false
- val nbMembers = GroupMaxSize + 1
-
- // JoinRequests
- var futures = 1.to(nbMembers).map { _ =>
- sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols,
- None, DefaultSessionTimeout, DefaultRebalanceTimeout, requiredKnownMemberId)
- }
-
- // advance clock by GroupInitialRebalanceDelay to complete first InitialDelayedJoin
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
- // advance clock by GroupInitialRebalanceDelay to complete second InitialDelayedJoin
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
-
- // Awaiting results
- val joinGroupResults = futures.map(await(_, DefaultRebalanceTimeout + 1))
- val errors = joinGroupResults.map(_.error)
-
- assertEquals(GroupMaxSize, errors.count(_ == Errors.NONE))
- assertEquals(nbMembers-GroupMaxSize, errors.count(_ == Errors.GROUP_MAX_SIZE_REACHED))
-
- // Members which were accepted can rejoin, others are rejected, while
- // completing rebalance
- val memberIds = joinGroupResults.map(_.memberId)
- futures = memberIds.map { memberId =>
- sendJoinGroup(groupId, memberId, protocolType, protocols,
- None, DefaultSessionTimeout, DefaultRebalanceTimeout, requiredKnownMemberId)
- }
-
- // Awaiting results
- val rejoinErrors = futures.map(await(_, 1).error)
-
- assertEquals(errors, rejoinErrors)
- }
-
- @Test
- def testStaticMembersJoinGroupWithMaxSize(): Unit = {
- val nbMembers = GroupMaxSize + 1
- val instanceIds = 1.to(nbMembers).map(i => Some(s"instance-id-$i"))
-
- // JoinRequests
- var futures = instanceIds.map { instanceId =>
- sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols,
- instanceId, DefaultSessionTimeout, DefaultRebalanceTimeout)
- }
-
- // advance clock by GroupInitialRebalanceDelay to complete first InitialDelayedJoin
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
- // advance clock by GroupInitialRebalanceDelay to complete second InitialDelayedJoin
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
-
- // Awaiting results
- val joinGroupResults = futures.map(await(_, DefaultRebalanceTimeout + 1))
- val errors = joinGroupResults.map(_.error)
-
- assertEquals(GroupMaxSize, errors.count(_ == Errors.NONE))
- assertEquals(nbMembers-GroupMaxSize, errors.count(_ == Errors.GROUP_MAX_SIZE_REACHED))
-
- // Members which were accepted can rejoin, others are rejected, while
- // completing rebalance
- val memberIds = joinGroupResults.map(_.memberId)
- futures = instanceIds.zip(memberIds).map { case (instanceId, memberId) =>
- sendJoinGroup(groupId, memberId, protocolType, protocols,
- instanceId, DefaultSessionTimeout, DefaultRebalanceTimeout)
- }
-
- // Awaiting results
- val rejoinErrors = futures.map(await(_, 1).error)
-
- assertEquals(errors, rejoinErrors)
- }
-
- @Test
- def testDynamicMembersCanReJoinGroupWithMaxSizeWhileRebalancing(): Unit = {
- val requiredKnownMemberId = true
- val nbMembers = GroupMaxSize + 1
-
- // First JoinRequests
- var futures = 1.to(nbMembers).map { _ =>
- sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols,
- None, DefaultSessionTimeout, DefaultRebalanceTimeout, requiredKnownMemberId)
- }
-
- // Get back the assigned member ids
- val memberIds = futures.map(await(_, 1).memberId)
-
- // Second JoinRequests
- memberIds.map { memberId =>
- sendJoinGroup(groupId, memberId, protocolType, protocols,
- None, DefaultSessionTimeout, DefaultRebalanceTimeout, requiredKnownMemberId)
- }
-
- // Members can rejoin while rebalancing
- futures = memberIds.map { memberId =>
- sendJoinGroup(groupId, memberId, protocolType, protocols,
- None, DefaultSessionTimeout, DefaultRebalanceTimeout, requiredKnownMemberId)
- }
-
- // advance clock by GroupInitialRebalanceDelay to complete first InitialDelayedJoin
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
- // advance clock by GroupInitialRebalanceDelay to complete second InitialDelayedJoin
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
-
- // Awaiting results
- val errors = futures.map(await(_, DefaultRebalanceTimeout + 1).error)
-
- assertEquals(GroupMaxSize, errors.count(_ == Errors.NONE))
- assertEquals(nbMembers-GroupMaxSize, errors.count(_ == Errors.GROUP_MAX_SIZE_REACHED))
- }
-
- @Test
- def testLastJoiningMembersAreKickedOutWhenReJoiningGroupWithMaxSize(): Unit = {
- val nbMembers = GroupMaxSize + 2
- val group = new GroupMetadata(groupId, Stable, new MockTime())
- val memberIds = 1.to(nbMembers).map(_ => group.generateMemberId(ClientId, None))
-
- memberIds.foreach { memberId =>
- group.add(new MemberMetadata(memberId, None, ClientId, ClientHost,
- DefaultRebalanceTimeout, GroupMaxSessionTimeout, protocolType, protocols))
- }
- groupCoordinator.groupManager.addGroup(group)
-
- groupCoordinator.prepareRebalance(group, "")
-
- val futures = memberIds.map { memberId =>
- sendJoinGroup(groupId, memberId, protocolType, protocols,
- None, GroupMaxSessionTimeout, DefaultRebalanceTimeout)
- }
-
- // advance clock by GroupInitialRebalanceDelay to complete first InitialDelayedJoin
- when(replicaManager.onlinePartition(any[TopicPartition]))
- .thenReturn(Some(mock(classOf[Partition])))
- timer.advanceClock(DefaultRebalanceTimeout + 1)
-
- // Awaiting results
- val errors = futures.map(await(_, DefaultRebalanceTimeout + 1).error)
-
- assertEquals(Set(Errors.NONE), errors.take(GroupMaxSize).toSet)
- assertEquals(Set(Errors.GROUP_MAX_SIZE_REACHED), errors.drop(GroupMaxSize).toSet)
-
- memberIds.drop(GroupMaxSize).foreach { memberId =>
- assertFalse(group.has(memberId))
- }
- }
-
- @Test
- def testJoinGroupSessionTimeoutTooSmall(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols, sessionTimeout = GroupMinSessionTimeout - 1)
- assertEquals(Errors.INVALID_SESSION_TIMEOUT, joinGroupResult.error)
- }
-
- @Test
- def testJoinGroupSessionTimeoutTooLarge(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols, sessionTimeout = GroupMaxSessionTimeout + 1)
- assertEquals(Errors.INVALID_SESSION_TIMEOUT, joinGroupResult.error)
- }
-
- @Test
- def testJoinGroupUnknownConsumerNewGroup(): Unit = {
- var joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- assertEquals(Errors.UNKNOWN_MEMBER_ID, joinGroupResult.error)
-
- joinGroupResult = staticJoinGroup(groupId, memberId, groupInstanceId, protocolType, protocols)
- assertEquals(Errors.UNKNOWN_MEMBER_ID, joinGroupResult.error)
- }
-
- @Test
- def testInvalidGroupId(): Unit = {
- val groupId = ""
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- assertEquals(Errors.INVALID_GROUP_ID, joinGroupResult.error)
- }
-
- @Test
- def testValidJoinGroup(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- assertEquals(Errors.NONE, joinGroupResult.error)
- }
-
- @Test
- def testJoinGroupInconsistentProtocolType(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val otherMemberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- assertEquals(Errors.NONE, joinGroupResult.error)
-
- val otherJoinGroupResult = await(sendJoinGroup(groupId, otherMemberId, "connect", protocols), 1)
- assertEquals(Errors.INCONSISTENT_GROUP_PROTOCOL, otherJoinGroupResult.error)
- }
-
- @Test
- def testJoinGroupWithEmptyProtocolType(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- var joinGroupResult = dynamicJoinGroup(groupId, memberId, "", protocols)
- assertEquals(Errors.INCONSISTENT_GROUP_PROTOCOL, joinGroupResult.error)
-
- joinGroupResult = staticJoinGroup(groupId, memberId, groupInstanceId, "", protocols)
- assertEquals(Errors.INCONSISTENT_GROUP_PROTOCOL, joinGroupResult.error)
- }
-
- @Test
- def testJoinGroupWithEmptyGroupProtocol(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, List())
- assertEquals(Errors.INCONSISTENT_GROUP_PROTOCOL, joinGroupResult.error)
- }
-
- @Test
- def testNewMemberTimeoutCompletion(): Unit = {
- val sessionTimeout = GroupCoordinator.NewMemberJoinTimeoutMs + 5000
- val responseFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols, None, sessionTimeout, DefaultRebalanceTimeout)
-
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
-
- val joinResult = Await.result(responseFuture, Duration(DefaultRebalanceTimeout + 100, TimeUnit.MILLISECONDS))
- val group = groupCoordinator.groupManager.getGroup(groupId).get
- val memberId = joinResult.memberId
-
- assertEquals(Errors.NONE, joinResult.error)
- assertEquals(0, group.allMemberMetadata.count(_.isNew))
-
- val syncGroupResult = syncGroupLeader(groupId, joinResult.generationId, memberId, Map(memberId -> Array[Byte]()))
- assertEquals(Errors.NONE, syncGroupResult.error)
- assertEquals(1, group.size)
-
- timer.advanceClock(GroupCoordinator.NewMemberJoinTimeoutMs + 100)
-
- // Make sure the NewMemberTimeout is not still in effect, and the member is not kicked
- assertEquals(1, group.size)
-
- timer.advanceClock(sessionTimeout + 100)
- assertEquals(0, group.size)
- }
-
- @Test
- def testNewMemberJoinExpiration(): Unit = {
- // This tests new member expiration during a protracted rebalance. We first create a
- // group with one member which uses a large value for session timeout and rebalance timeout.
- // We then join with one new member and let the rebalance hang while we await the first member.
- // The new member join timeout expires and its JoinGroup request is failed.
-
- val sessionTimeout = GroupCoordinator.NewMemberJoinTimeoutMs + 5000
- val rebalanceTimeout = GroupCoordinator.NewMemberJoinTimeoutMs * 2
-
- val firstJoinResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols,
- sessionTimeout, rebalanceTimeout)
- val firstMemberId = firstJoinResult.memberId
- assertEquals(firstMemberId, firstJoinResult.leaderId)
- assertEquals(Errors.NONE, firstJoinResult.error)
-
- val groupOpt = groupCoordinator.groupManager.getGroup(groupId)
- assertTrue(groupOpt.isDefined)
- val group = groupOpt.get
- assertEquals(0, group.allMemberMetadata.count(_.isNew))
-
- val responseFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols, None, sessionTimeout, rebalanceTimeout)
- assertFalse(responseFuture.isCompleted)
-
- assertEquals(2, group.allMembers.size)
- assertEquals(1, group.allMemberMetadata.count(_.isNew))
-
- val newMember = group.allMemberMetadata.find(_.isNew).get
- assertNotEquals(firstMemberId, newMember.memberId)
-
- timer.advanceClock(GroupCoordinator.NewMemberJoinTimeoutMs + 1)
- assertTrue(responseFuture.isCompleted)
-
- val response = Await.result(responseFuture, Duration(0, TimeUnit.MILLISECONDS))
- assertEquals(Errors.UNKNOWN_MEMBER_ID, response.error)
- assertEquals(1, group.allMembers.size)
- assertEquals(0, group.allMemberMetadata.count(_.isNew))
- assertEquals(firstMemberId, group.allMembers.head)
- }
-
- @Test
- def testNewMemberFailureAfterJoinGroupCompletion(): Unit = {
- // For old versions of the JoinGroup protocol, new members were subject
- // to expiration if the rebalance took long enough. This test case ensures
- // that following completion of the JoinGroup phase, new members follow
- // normal heartbeat expiration logic.
-
- val firstJoinResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val firstMemberId = firstJoinResult.memberId
- val firstGenerationId = firstJoinResult.generationId
- assertEquals(firstMemberId, firstJoinResult.leaderId)
- assertEquals(Errors.NONE, firstJoinResult.error)
-
- val firstSyncResult = syncGroupLeader(groupId, firstGenerationId, firstMemberId,
- Map(firstMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, firstSyncResult.error)
-
- val otherJoinFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
-
- val joinFuture = sendJoinGroup(groupId, firstMemberId, protocolType, protocols)
-
- val joinResult = await(joinFuture, DefaultSessionTimeout+100)
- val otherJoinResult = await(otherJoinFuture, DefaultSessionTimeout+100)
- assertEquals(Errors.NONE, joinResult.error)
- assertEquals(Errors.NONE, otherJoinResult.error)
-
- verifySessionExpiration(groupId)
- }
-
- @Test
- def testNewMemberFailureAfterSyncGroupCompletion(): Unit = {
- // For old versions of the JoinGroup protocol, new members were subject
- // to expiration if the rebalance took long enough. This test case ensures
- // that following completion of the SyncGroup phase, new members follow
- // normal heartbeat expiration logic.
-
- val firstJoinResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val firstMemberId = firstJoinResult.memberId
- val firstGenerationId = firstJoinResult.generationId
- assertEquals(firstMemberId, firstJoinResult.leaderId)
- assertEquals(Errors.NONE, firstJoinResult.error)
-
- val firstSyncResult = syncGroupLeader(groupId, firstGenerationId, firstMemberId,
- Map(firstMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, firstSyncResult.error)
-
- val otherJoinFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
-
- val joinFuture = sendJoinGroup(groupId, firstMemberId, protocolType, protocols)
-
- val joinResult = await(joinFuture, DefaultSessionTimeout+100)
- val otherJoinResult = await(otherJoinFuture, DefaultSessionTimeout+100)
- assertEquals(Errors.NONE, joinResult.error)
- assertEquals(Errors.NONE, otherJoinResult.error)
- val secondGenerationId = joinResult.generationId
- val secondMemberId = otherJoinResult.memberId
-
- sendSyncGroupFollower(groupId, secondGenerationId, secondMemberId)
-
- val syncGroupResult = syncGroupLeader(groupId, secondGenerationId, firstMemberId,
- Map(firstMemberId -> Array.emptyByteArray, secondMemberId -> Array.emptyByteArray))
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- verifySessionExpiration(groupId)
- }
-
- private def verifySessionExpiration(groupId: String): Unit = {
- when(replicaManager.onlinePartition(any[TopicPartition]))
- .thenReturn(Some(mock(classOf[Partition])))
-
- timer.advanceClock(DefaultSessionTimeout + 1)
-
- val groupMetadata = group(groupId)
- assertEquals(Empty, groupMetadata.currentState)
- assertTrue(groupMetadata.allMembers.isEmpty)
- }
-
- @Test
- def testJoinGroupInconsistentGroupProtocol(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val otherMemberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupFuture = sendJoinGroup(groupId, memberId, protocolType, List(("range", metadata)))
-
- val otherJoinGroupResult = dynamicJoinGroup(groupId, otherMemberId, protocolType, List(("roundrobin", metadata)))
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
-
- val joinGroupResult = await(joinGroupFuture, 1)
- assertEquals(Errors.NONE, joinGroupResult.error)
- assertEquals(Errors.INCONSISTENT_GROUP_PROTOCOL, otherJoinGroupResult.error)
- }
-
- @Test
- def testJoinGroupUnknownConsumerExistingGroup(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val otherMemberId = "memberId"
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- assertEquals(Errors.NONE, joinGroupResult.error)
-
- val otherJoinGroupResult = await(sendJoinGroup(groupId, otherMemberId, protocolType, protocols), 1)
- assertEquals(Errors.UNKNOWN_MEMBER_ID, otherJoinGroupResult.error)
- }
-
- @Test
- def testJoinGroupUnknownConsumerNewDeadGroup(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val deadGroupId = "deadGroupId"
-
- groupCoordinator.groupManager.addGroup(new GroupMetadata(deadGroupId, Dead, new MockTime()))
- val joinGroupResult = dynamicJoinGroup(deadGroupId, memberId, protocolType, protocols)
- assertEquals(Errors.COORDINATOR_NOT_AVAILABLE, joinGroupResult.error)
- }
-
- @Test
- def testSyncDeadGroup(): Unit = {
- val memberId = "memberId"
- val deadGroupId = "deadGroupId"
-
- groupCoordinator.groupManager.addGroup(new GroupMetadata(deadGroupId, Dead, new MockTime()))
- val syncGroupResult = syncGroupFollower(deadGroupId, 1, memberId)
- assertEquals(Errors.COORDINATOR_NOT_AVAILABLE, syncGroupResult.error)
- }
-
- @Test
- def testJoinGroupSecondJoinInconsistentProtocol(): Unit = {
- var responseFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols, requireKnownMemberId = true)
- var joinGroupResult = Await.result(responseFuture, Duration(DefaultRebalanceTimeout + 1, TimeUnit.MILLISECONDS))
- assertEquals(Errors.MEMBER_ID_REQUIRED, joinGroupResult.error)
- val memberId = joinGroupResult.memberId
-
- // Sending an inconsistent protocol shall be refused
- responseFuture = sendJoinGroup(groupId, memberId, protocolType, List(), requireKnownMemberId = true)
- joinGroupResult = Await.result(responseFuture, Duration(DefaultRebalanceTimeout + 1, TimeUnit.MILLISECONDS))
- assertEquals(Errors.INCONSISTENT_GROUP_PROTOCOL, joinGroupResult.error)
-
- // Sending consistent protocol shall be accepted
- responseFuture = sendJoinGroup(groupId, memberId, protocolType, protocols, requireKnownMemberId = true)
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
- joinGroupResult = Await.result(responseFuture, Duration(DefaultRebalanceTimeout + 1, TimeUnit.MILLISECONDS))
- assertEquals(Errors.NONE, joinGroupResult.error)
- }
-
- @Test
- def staticMemberJoinAsFirstMember(): Unit = {
- val joinGroupResult = staticJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, groupInstanceId, protocolType, protocols)
- assertEquals(Errors.NONE, joinGroupResult.error)
- }
-
- @Test
- def staticMemberReJoinWithExplicitUnknownMemberId(): Unit = {
- var joinGroupResult = staticJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, groupInstanceId, protocolType, protocols)
- assertEquals(Errors.NONE, joinGroupResult.error)
-
- val unknownMemberId = "unknown_member"
- joinGroupResult = staticJoinGroup(groupId, unknownMemberId, groupInstanceId, protocolType, protocols)
- assertEquals(Errors.FENCED_INSTANCE_ID, joinGroupResult.error)
- }
-
- @Test
- def staticMemberFenceDuplicateRejoinedFollower(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- // A third member joins will trigger rebalance.
- sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- timer.advanceClock(1)
- assertTrue(getGroup(groupId).is(PreparingRebalance))
-
- timer.advanceClock(1)
- // Old follower rejoins group will be matching current member.id.
- val oldFollowerJoinGroupFuture =
- sendJoinGroup(groupId, rebalanceResult.followerId, protocolType, protocols, groupInstanceId = Some(followerInstanceId))
-
- timer.advanceClock(1)
- // Duplicate follower joins group with unknown member id will trigger member.id replacement.
- val duplicateFollowerJoinFuture =
- sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols, groupInstanceId = Some(followerInstanceId))
-
- timer.advanceClock(1)
- // Old member shall be fenced immediately upon duplicate follower joins.
- val oldFollowerJoinGroupResult = Await.result(oldFollowerJoinGroupFuture, Duration(1, TimeUnit.MILLISECONDS))
- checkJoinGroupResult(oldFollowerJoinGroupResult,
- Errors.FENCED_INSTANCE_ID,
- -1,
- Set.empty,
- PreparingRebalance,
- None)
- verifyDelayedTaskNotCompleted(duplicateFollowerJoinFuture)
- }
-
- @Test
- def staticMemberFenceDuplicateSyncingFollowerAfterMemberIdChanged(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- // Known leader rejoins will trigger rebalance.
- val leaderJoinGroupFuture =
- sendJoinGroup(groupId, rebalanceResult.leaderId, protocolType, protocols, groupInstanceId = Some(leaderInstanceId))
- timer.advanceClock(1)
- assertTrue(getGroup(groupId).is(PreparingRebalance))
-
- timer.advanceClock(1)
- // Old follower rejoins group will match current member.id.
- val oldFollowerJoinGroupFuture =
- sendJoinGroup(groupId, rebalanceResult.followerId, protocolType, protocols, groupInstanceId = Some(followerInstanceId))
-
- timer.advanceClock(1)
- val leaderJoinGroupResult = Await.result(leaderJoinGroupFuture, Duration(1, TimeUnit.MILLISECONDS))
- checkJoinGroupResult(leaderJoinGroupResult,
- Errors.NONE,
- rebalanceResult.generation + 1,
- Set(leaderInstanceId, followerInstanceId),
- CompletingRebalance,
- Some(protocolType))
- assertEquals(rebalanceResult.leaderId, leaderJoinGroupResult.memberId)
- assertEquals(rebalanceResult.leaderId, leaderJoinGroupResult.leaderId)
-
- // Old follower shall be getting a successful join group response.
- val oldFollowerJoinGroupResult = Await.result(oldFollowerJoinGroupFuture, Duration(1, TimeUnit.MILLISECONDS))
- checkJoinGroupResult(oldFollowerJoinGroupResult,
- Errors.NONE,
- rebalanceResult.generation + 1,
- Set.empty,
- CompletingRebalance,
- Some(protocolType),
- expectedLeaderId = leaderJoinGroupResult.memberId)
- assertEquals(rebalanceResult.followerId, oldFollowerJoinGroupResult.memberId)
- assertEquals(rebalanceResult.leaderId, oldFollowerJoinGroupResult.leaderId)
- assertTrue(getGroup(groupId).is(CompletingRebalance))
-
- // Duplicate follower joins group with unknown member id will trigger member.id replacement,
- // and will also trigger a rebalance under CompletingRebalance state; the old follower sync callback
- // will return fenced exception while broker replaces the member identity with the duplicate follower joins.
- val oldFollowerSyncGroupFuture = sendSyncGroupFollower(groupId, oldFollowerJoinGroupResult.generationId,
- oldFollowerJoinGroupResult.memberId, Some(protocolType), Some(protocolName), Some(followerInstanceId))
-
- val duplicateFollowerJoinFuture =
- sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols, groupInstanceId = Some(followerInstanceId))
- timer.advanceClock(1)
-
- val oldFollowerSyncGroupResult = Await.result(oldFollowerSyncGroupFuture, Duration(1, TimeUnit.MILLISECONDS))
- assertEquals(Errors.FENCED_INSTANCE_ID, oldFollowerSyncGroupResult.error)
- assertTrue(getGroup(groupId).is(PreparingRebalance))
-
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
- timer.advanceClock(DefaultRebalanceTimeout + 1)
-
- val duplicateFollowerJoinGroupResult = Await.result(duplicateFollowerJoinFuture, Duration(1, TimeUnit.MILLISECONDS))
- checkJoinGroupResult(duplicateFollowerJoinGroupResult,
- Errors.NONE,
- rebalanceResult.generation + 2,
- Set(followerInstanceId), // this follower will become the new leader, and hence it would have the member list
- CompletingRebalance,
- Some(protocolType),
- expectedLeaderId = duplicateFollowerJoinGroupResult.memberId)
- assertTrue(getGroup(groupId).is(CompletingRebalance))
- }
-
- @Test
- def staticMemberFenceDuplicateRejoiningFollowerAfterMemberIdChanged(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- // Known leader rejoins will trigger rebalance.
- val leaderJoinGroupFuture =
- sendJoinGroup(groupId, rebalanceResult.leaderId, protocolType, protocols, groupInstanceId = Some(leaderInstanceId))
- timer.advanceClock(1)
- assertTrue(getGroup(groupId).is(PreparingRebalance))
-
- // Duplicate follower joins group will trigger member.id replacement.
- val duplicateFollowerJoinGroupFuture =
- sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols, groupInstanceId = Some(followerInstanceId))
-
- timer.advanceClock(1)
- // Old follower rejoins group will fail because member.id already updated.
- val oldFollowerJoinGroupFuture =
- sendJoinGroup(groupId, rebalanceResult.followerId, protocolType, protocols, groupInstanceId = Some(followerInstanceId))
-
- val leaderRejoinGroupResult = Await.result(leaderJoinGroupFuture, Duration(1, TimeUnit.MILLISECONDS))
- checkJoinGroupResult(leaderRejoinGroupResult,
- Errors.NONE,
- rebalanceResult.generation + 1,
- Set(leaderInstanceId, followerInstanceId),
- CompletingRebalance,
- Some(protocolType))
-
- val duplicateFollowerJoinGroupResult = Await.result(duplicateFollowerJoinGroupFuture, Duration(1, TimeUnit.MILLISECONDS))
- checkJoinGroupResult(duplicateFollowerJoinGroupResult,
- Errors.NONE,
- rebalanceResult.generation + 1,
- Set.empty,
- CompletingRebalance,
- Some(protocolType))
- assertNotEquals(rebalanceResult.followerId, duplicateFollowerJoinGroupResult.memberId)
-
- val oldFollowerJoinGroupResult = Await.result(oldFollowerJoinGroupFuture, Duration(1, TimeUnit.MILLISECONDS))
- checkJoinGroupResult(oldFollowerJoinGroupResult,
- Errors.FENCED_INSTANCE_ID,
- -1,
- Set.empty,
- CompletingRebalance,
- None)
- }
-
- @Test
- def staticMemberRejoinWithKnownMemberId(): Unit = {
- var joinGroupResult = staticJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, groupInstanceId, protocolType, protocols)
- assertEquals(Errors.NONE, joinGroupResult.error)
-
- val assignedMemberId = joinGroupResult.memberId
- // The second join group should return immediately since we are using the same metadata during CompletingRebalance.
- val rejoinResponseFuture = sendJoinGroup(groupId, assignedMemberId, protocolType, protocols, Some(groupInstanceId))
- timer.advanceClock(1)
- joinGroupResult = Await.result(rejoinResponseFuture, Duration(1, TimeUnit.MILLISECONDS))
- assertEquals(Errors.NONE, joinGroupResult.error)
- assertTrue(getGroup(groupId).is(CompletingRebalance))
-
- val syncGroupFuture = sendSyncGroupLeader(groupId, joinGroupResult.generationId, assignedMemberId,
- Some(protocolType), Some(protocolName), Some(groupInstanceId), Map(assignedMemberId -> Array[Byte]()))
- timer.advanceClock(1)
- val syncGroupResult = Await.result(syncGroupFuture, Duration(1, TimeUnit.MILLISECONDS))
- assertEquals(Errors.NONE, syncGroupResult.error)
- assertTrue(getGroup(groupId).is(Stable))
- }
-
- @ParameterizedTest
- @ValueSource(booleans = Array(true, false))
- def staticMemberRejoinWithLeaderIdAndUnknownMemberId(supportSkippingAssignment: Boolean): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- // A static leader rejoin with unknown id will not trigger rebalance, and no assignment will be returned.
- val joinGroupResult = staticJoinGroupWithPersistence(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID,
- leaderInstanceId, protocolType, protocolSuperset, clockAdvance = 1, supportSkippingAssignment = supportSkippingAssignment)
-
- checkJoinGroupResult(joinGroupResult,
- Errors.NONE,
- rebalanceResult.generation, // The group should be at the same generation
- if (supportSkippingAssignment) Set(leaderInstanceId, followerInstanceId) else Set.empty,
- Stable,
- Some(protocolType),
- if (supportSkippingAssignment) joinGroupResult.memberId else rebalanceResult.leaderId,
- expectedSkipAssignment = supportSkippingAssignment
- )
-
- val oldLeaderJoinGroupResult = staticJoinGroup(groupId, rebalanceResult.leaderId, leaderInstanceId, protocolType, protocolSuperset, clockAdvance = 1)
- assertEquals(Errors.FENCED_INSTANCE_ID, oldLeaderJoinGroupResult.error)
-
- // Old leader will get fenced.
- val oldLeaderSyncGroupResult = syncGroupLeader(groupId, rebalanceResult.generation, rebalanceResult.leaderId,
- Map.empty, None, None, Some(leaderInstanceId))
- assertEquals(Errors.FENCED_INSTANCE_ID, oldLeaderSyncGroupResult.error)
-
- // Calling sync on old leader.id will fail because that leader.id is no longer valid and replaced.
- val newLeaderSyncGroupResult = syncGroupLeader(groupId, rebalanceResult.generation, rebalanceResult.leaderId, Map.empty)
- assertEquals(Errors.UNKNOWN_MEMBER_ID, newLeaderSyncGroupResult.error)
- }
-
- @Test
- def staticMemberRejoinWithLeaderIdAndKnownMemberId(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId,
- sessionTimeout = DefaultRebalanceTimeout / 2)
-
- // A static leader with known id rejoin will trigger rebalance.
- val joinGroupResult = staticJoinGroup(groupId, rebalanceResult.leaderId, leaderInstanceId,
- protocolType, protocolSuperset, clockAdvance = DefaultRebalanceTimeout + 1)
- // Timeout follower in the meantime.
- assertFalse(getGroup(groupId).hasStaticMember(followerInstanceId))
- checkJoinGroupResult(joinGroupResult,
- Errors.NONE,
- rebalanceResult.generation + 1, // The group has promoted to the new generation.
- Set(leaderInstanceId),
- CompletingRebalance,
- Some(protocolType),
- rebalanceResult.leaderId,
- rebalanceResult.leaderId)
- }
-
- @Test
- def staticMemberRejoinWithLeaderIdAndUnexpectedDeadGroup(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- getGroup(groupId).transitionTo(Dead)
-
- val joinGroupResult = staticJoinGroup(groupId, rebalanceResult.leaderId, leaderInstanceId, protocolType, protocols, clockAdvance = 1)
- assertEquals(Errors.COORDINATOR_NOT_AVAILABLE, joinGroupResult.error)
- }
-
- @Test
- def staticMemberRejoinWithLeaderIdAndUnexpectedEmptyGroup(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- getGroup(groupId).transitionTo(PreparingRebalance)
- getGroup(groupId).transitionTo(Empty)
-
- val joinGroupResult = staticJoinGroup(groupId, rebalanceResult.leaderId, leaderInstanceId, protocolType, protocols, clockAdvance = 1)
- assertEquals(Errors.UNKNOWN_MEMBER_ID, joinGroupResult.error)
- }
-
- @Test
- def staticMemberRejoinWithFollowerIdAndChangeOfProtocol(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId, sessionTimeout = DefaultSessionTimeout * 2)
-
- // A static follower rejoin with changed protocol will trigger rebalance.
- val newProtocols = List(("roundrobin", metadata))
- // Old leader hasn't joined in the meantime, triggering a re-election.
- val joinGroupResult = staticJoinGroup(groupId, rebalanceResult.followerId, followerInstanceId, protocolType, newProtocols, clockAdvance = DefaultSessionTimeout + 1)
-
- assertEquals(rebalanceResult.followerId, joinGroupResult.memberId)
- assertTrue(getGroup(groupId).hasStaticMember(leaderInstanceId))
- assertTrue(getGroup(groupId).isLeader(rebalanceResult.followerId))
- checkJoinGroupResult(joinGroupResult,
- Errors.NONE,
- rebalanceResult.generation + 1, // The group has promoted to the new generation, and leader has changed because old one times out.
- Set(leaderInstanceId, followerInstanceId),
- CompletingRebalance,
- Some(protocolType),
- rebalanceResult.followerId,
- rebalanceResult.followerId)
- }
-
- @Test
- def staticMemberRejoinWithUnknownMemberIdAndChangeOfProtocolWithSelectedProtocolChanged(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- // A static follower rejoin with protocol changed and also cause updated group's selectedProtocol changed
- // should trigger rebalance.
- val selectedProtocols = getGroup(groupId).selectProtocol
- val newProtocols = List(("roundrobin", metadata))
- assert(!newProtocols.map(_._1).contains(selectedProtocols))
- // Old leader hasn't joined in the meantime, triggering a re-election.
- val joinGroupResult = staticJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, followerInstanceId, protocolType, newProtocols, clockAdvance = DefaultSessionTimeout + 1)
-
- checkJoinGroupResult(joinGroupResult,
- Errors.NONE,
- rebalanceResult.generation + 1,
- Set(leaderInstanceId, followerInstanceId),
- CompletingRebalance,
- Some(protocolType))
-
- assertTrue(getGroup(groupId).isLeader(joinGroupResult.memberId))
- assertNotEquals(rebalanceResult.followerId, joinGroupResult.memberId)
- assertEquals(joinGroupResult.protocolName, Some("roundrobin"))
- }
-
- @Test
- def staticMemberRejoinWithUnknownMemberIdAndChangeOfProtocolWhileSelectProtocolUnchangedPersistenceFailure(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- val selectedProtocol = getGroup(groupId).selectProtocol
- val newProtocols = List((selectedProtocol, metadata))
- // Timeout old leader in the meantime.
- val joinGroupResult = staticJoinGroupWithPersistence(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID,
- followerInstanceId, protocolType, newProtocols, clockAdvance = 1, appendRecordError = Errors.MESSAGE_TOO_LARGE)
-
- checkJoinGroupResult(joinGroupResult,
- Errors.UNKNOWN_SERVER_ERROR,
- rebalanceResult.generation,
- Set.empty,
- Stable,
- Some(protocolType))
-
- // Join with old member id will not fail because the member id is not updated because of persistence failure
- assertNotEquals(rebalanceResult.followerId, joinGroupResult.memberId)
- val oldFollowerJoinGroupResult = staticJoinGroup(groupId, rebalanceResult.followerId, followerInstanceId, protocolType, newProtocols, clockAdvance = 1)
- assertEquals(Errors.NONE, oldFollowerJoinGroupResult.error)
-
- // Sync with old member id will also not fail because the member id is not updated because of persistence failure
- val syncGroupWithOldMemberIdResult = syncGroupFollower(groupId, rebalanceResult.generation,
- rebalanceResult.followerId, None, None, Some(followerInstanceId))
- assertEquals(Errors.NONE, syncGroupWithOldMemberIdResult.error)
- }
-
- @Test
- def staticMemberRejoinWithUpdatedSessionAndRebalanceTimeoutsButCannotPersistChange(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
- val joinGroupResult = staticJoinGroupWithPersistence(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, followerInstanceId, protocolType, protocolSuperset, clockAdvance = 1, 2 * DefaultSessionTimeout, 2 * DefaultRebalanceTimeout, appendRecordError = Errors.MESSAGE_TOO_LARGE)
- checkJoinGroupResult(joinGroupResult,
- Errors.UNKNOWN_SERVER_ERROR,
- rebalanceResult.generation,
- Set.empty,
- Stable,
- Some(protocolType))
- assertTrue(groupCoordinator.groupManager.getGroup(groupId).isDefined)
- val group = groupCoordinator.groupManager.getGroup(groupId).get
- group.allMemberMetadata.foreach { member =>
- assertEquals(member.sessionTimeoutMs, DefaultSessionTimeout)
- assertEquals(member.rebalanceTimeoutMs, DefaultRebalanceTimeout)
- }
- }
-
-
- @Test
- def staticMemberRejoinWithUpdatedSessionAndRebalanceTimeoutsAndPersistChange(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
- val followerJoinGroupResult = staticJoinGroupWithPersistence(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, followerInstanceId, protocolType, protocolSuperset, clockAdvance = 1, 2 * DefaultSessionTimeout, 2 * DefaultRebalanceTimeout)
- checkJoinGroupResult(followerJoinGroupResult,
- Errors.NONE,
- rebalanceResult.generation,
- Set.empty,
- Stable,
- Some(protocolType))
- val leaderJoinGroupResult = staticJoinGroupWithPersistence(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, leaderInstanceId, protocolType, protocolSuperset, clockAdvance = 1, 2 * DefaultSessionTimeout, 2 * DefaultRebalanceTimeout)
- checkJoinGroupResult(leaderJoinGroupResult,
- Errors.NONE,
- rebalanceResult.generation,
- Set(leaderInstanceId, followerInstanceId),
- Stable,
- Some(protocolType),
- leaderJoinGroupResult.leaderId,
- leaderJoinGroupResult.memberId,
- expectedSkipAssignment = true)
- assertTrue(groupCoordinator.groupManager.getGroup(groupId).isDefined)
- val group = groupCoordinator.groupManager.getGroup(groupId).get
- group.allMemberMetadata.foreach { member =>
- assertEquals(member.sessionTimeoutMs, 2 * DefaultSessionTimeout)
- assertEquals(member.rebalanceTimeoutMs, 2 * DefaultRebalanceTimeout)
- }
- }
- @Test
- def staticMemberRejoinWithUnknownMemberIdAndChangeOfProtocolWhileSelectProtocolUnchanged(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- // A static follower rejoin with protocol changing to leader protocol subset won't trigger rebalance if updated
- // group's selectProtocol remain unchanged.
- val selectedProtocol = getGroup(groupId).selectProtocol
- val newProtocols = List((selectedProtocol, metadata))
- // Timeout old leader in the meantime.
- val joinGroupResult = staticJoinGroupWithPersistence(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID,
- followerInstanceId, protocolType, newProtocols, clockAdvance = 1)
-
- checkJoinGroupResult(joinGroupResult,
- Errors.NONE,
- rebalanceResult.generation,
- Set.empty,
- Stable,
- Some(protocolType))
-
- // Join with old member id will fail because the member id is updated
- assertNotEquals(rebalanceResult.followerId, joinGroupResult.memberId)
- val oldFollowerJoinGroupResult = staticJoinGroup(groupId, rebalanceResult.followerId, followerInstanceId, protocolType, newProtocols, clockAdvance = 1)
- assertEquals(Errors.FENCED_INSTANCE_ID, oldFollowerJoinGroupResult.error)
-
- // Sync with old member id will fail because the member id is updated
- val syncGroupWithOldMemberIdResult = syncGroupFollower(groupId, rebalanceResult.generation,
- rebalanceResult.followerId, None, None, Some(followerInstanceId))
- assertEquals(Errors.FENCED_INSTANCE_ID, syncGroupWithOldMemberIdResult.error)
-
- val syncGroupWithNewMemberIdResult = syncGroupFollower(groupId, rebalanceResult.generation,
- joinGroupResult.memberId, None, None, Some(followerInstanceId))
- assertEquals(Errors.NONE, syncGroupWithNewMemberIdResult.error)
- assertEquals(rebalanceResult.followerAssignment, syncGroupWithNewMemberIdResult.memberAssignment)
- }
-
- @Test
- def staticMemberRejoinWithKnownLeaderIdToTriggerRebalanceAndFollowerWithChangeOfProtocol(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- // A static leader rejoin with known member id will trigger rebalance.
- val leaderRejoinGroupFuture = sendJoinGroup(groupId, rebalanceResult.leaderId, protocolType,
- protocolSuperset, Some(leaderInstanceId))
- // Rebalance complete immediately after follower rejoin.
- val followerRejoinWithFuture = sendJoinGroup(groupId, rebalanceResult.followerId, protocolType,
- protocolSuperset, Some(followerInstanceId))
-
- timer.advanceClock(1)
-
- // Leader should get the same assignment as last round.
- checkJoinGroupResult(await(leaderRejoinGroupFuture, 1),
- Errors.NONE,
- rebalanceResult.generation + 1, // The group has promoted to the new generation.
- Set(leaderInstanceId, followerInstanceId),
- CompletingRebalance,
- Some(protocolType),
- rebalanceResult.leaderId,
- rebalanceResult.leaderId)
-
- checkJoinGroupResult(await(followerRejoinWithFuture, 1),
- Errors.NONE,
- rebalanceResult.generation + 1, // The group has promoted to the new generation.
- Set.empty,
- CompletingRebalance,
- Some(protocolType),
- rebalanceResult.leaderId,
- rebalanceResult.followerId)
-
- // The follower protocol changed from protocolSuperset to general protocols.
- val followerRejoinWithProtocolChangeFuture = sendJoinGroup(groupId, rebalanceResult.followerId,
- protocolType, protocols, Some(followerInstanceId))
- // The group will transit to PreparingRebalance due to protocol change from follower.
- assertTrue(getGroup(groupId).is(PreparingRebalance))
-
- timer.advanceClock(DefaultRebalanceTimeout + 1)
- checkJoinGroupResult(await(followerRejoinWithProtocolChangeFuture, 1),
- Errors.NONE,
- rebalanceResult.generation + 2, // The group has promoted to the new generation.
- Set(followerInstanceId),
- CompletingRebalance,
- Some(protocolType),
- rebalanceResult.followerId,
- rebalanceResult.followerId)
- }
-
- @Test
- def staticMemberRejoinAsFollowerWithUnknownMemberId(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- // A static follower rejoin with no protocol change will not trigger rebalance.
- val joinGroupResult = staticJoinGroupWithPersistence(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, followerInstanceId, protocolType, protocolSuperset, clockAdvance = 1)
-
- // Old leader shouldn't be timed out.
- assertTrue(getGroup(groupId).hasStaticMember(leaderInstanceId))
- checkJoinGroupResult(joinGroupResult,
- Errors.NONE,
- rebalanceResult.generation, // The group has no change.
- Set.empty,
- Stable,
- Some(protocolType))
-
- assertNotEquals(rebalanceResult.followerId, joinGroupResult.memberId)
-
- val syncGroupResult = syncGroupFollower(groupId, rebalanceResult.generation, joinGroupResult.memberId)
- assertEquals(Errors.NONE, syncGroupResult.error)
- assertEquals(rebalanceResult.followerAssignment, syncGroupResult.memberAssignment)
- }
-
- @Test
- def staticMemberRejoinAsFollowerWithKnownMemberIdAndNoProtocolChange(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- // A static follower rejoin with no protocol change will not trigger rebalance.
- val joinGroupResult = staticJoinGroup(groupId, rebalanceResult.followerId, followerInstanceId, protocolType, protocolSuperset, clockAdvance = 1)
-
- // Old leader shouldn't be timed out.
- assertTrue(getGroup(groupId).hasStaticMember(leaderInstanceId))
- checkJoinGroupResult(joinGroupResult,
- Errors.NONE,
- rebalanceResult.generation, // The group has no change.
- Set.empty,
- Stable,
- Some(protocolType),
- rebalanceResult.leaderId,
- rebalanceResult.followerId)
- }
-
- @Test
- def staticMemberRejoinAsFollowerWithMismatchedMemberId(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- val joinGroupResult = staticJoinGroup(groupId, rebalanceResult.followerId, leaderInstanceId, protocolType, protocolSuperset, clockAdvance = 1)
- assertEquals(Errors.FENCED_INSTANCE_ID, joinGroupResult.error)
- }
-
- @Test
- def staticMemberRejoinAsLeaderWithMismatchedMemberId(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- val joinGroupResult = staticJoinGroup(groupId, rebalanceResult.leaderId, followerInstanceId, protocolType, protocolSuperset, clockAdvance = 1)
- assertEquals(Errors.FENCED_INSTANCE_ID, joinGroupResult.error)
- }
-
- @Test
- def staticMemberSyncAsLeaderWithInvalidMemberId(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- val syncGroupResult = syncGroupLeader(groupId, rebalanceResult.generation, "invalid",
- Map.empty, None, None, Some(leaderInstanceId))
- assertEquals(Errors.FENCED_INSTANCE_ID, syncGroupResult.error)
- }
-
- @Test
- def staticMemberHeartbeatLeaderWithInvalidMemberId(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- val syncGroupResult = syncGroupLeader(groupId, rebalanceResult.generation, rebalanceResult.leaderId, Map.empty)
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- val validHeartbeatResult = heartbeat(groupId, rebalanceResult.leaderId, rebalanceResult.generation)
- assertEquals(Errors.NONE, validHeartbeatResult)
-
- val invalidHeartbeatResult = heartbeat(groupId, invalidMemberId, rebalanceResult.generation, Some(leaderInstanceId))
- assertEquals(Errors.FENCED_INSTANCE_ID, invalidHeartbeatResult)
- }
-
- @Test
- def shouldGetDifferentStaticMemberIdAfterEachRejoin(): Unit = {
- val initialResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- val timeAdvance = 1
- var lastMemberId = initialResult.leaderId
- for (_ <- 1 to 5) {
- val joinGroupResult = staticJoinGroupWithPersistence(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID,
- leaderInstanceId, protocolType, protocols, clockAdvance = timeAdvance)
- assertTrue(joinGroupResult.memberId.startsWith(leaderInstanceId))
- assertNotEquals(lastMemberId, joinGroupResult.memberId)
- lastMemberId = joinGroupResult.memberId
- }
- }
-
- @Test
- def testOffsetCommitDeadGroup(): Unit = {
- val memberId = "memberId"
-
- val deadGroupId = "deadGroupId"
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
-
- groupCoordinator.groupManager.addGroup(new GroupMetadata(deadGroupId, Dead, new MockTime()))
- val offsetCommitResult = commitOffsets(deadGroupId, memberId, 1, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.COORDINATOR_NOT_AVAILABLE), offsetCommitResult)
- }
-
- @Test
- def staticMemberCommitOffsetWithInvalidMemberId(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- val syncGroupResult = syncGroupLeader(groupId, rebalanceResult.generation, rebalanceResult.leaderId, Map.empty)
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
- val validOffsetCommitResult = commitOffsets(groupId, rebalanceResult.leaderId, rebalanceResult.generation, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.NONE), validOffsetCommitResult)
-
- val invalidOffsetCommitResult = commitOffsets(groupId, invalidMemberId, rebalanceResult.generation,
- Map(tip -> offset), Some(leaderInstanceId))
- assertEquals(Map(tip -> Errors.FENCED_INSTANCE_ID), invalidOffsetCommitResult)
- }
-
- @Test
- def staticMemberJoinWithUnknownInstanceIdAndKnownMemberId(): Unit = {
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- val joinGroupResult = staticJoinGroup(groupId, rebalanceResult.leaderId, "unknown_instance",
- protocolType, protocolSuperset, clockAdvance = 1)
-
- assertEquals(Errors.UNKNOWN_MEMBER_ID, joinGroupResult.error)
- }
-
- @Test
- def staticMemberReJoinWithIllegalStateAsUnknownMember(): Unit = {
- staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
- val group = groupCoordinator.groupManager.getGroup(groupId).get
- group.transitionTo(PreparingRebalance)
- group.transitionTo(Empty)
-
- // Illegal state exception shall trigger since follower id resides in pending member bucket.
- val expectedException = assertThrows(classOf[IllegalStateException],
- () => staticJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, followerInstanceId, protocolType, protocolSuperset, clockAdvance = 1))
-
- val message = expectedException.getMessage
- assertTrue(message.contains(group.groupId))
- assertTrue(message.contains(followerInstanceId))
- }
-
- @Test
- def testLeaderFailToRejoinBeforeFinalRebalanceTimeoutWithLongSessionTimeout(): Unit = {
- groupStuckInRebalanceTimeoutDueToNonjoinedStaticMember()
-
- timer.advanceClock(DefaultRebalanceTimeout + 1)
- // The static leader should already session timeout, moving group towards Empty
- assertEquals(Set.empty, getGroup(groupId).allMembers)
- assertNull(getGroup(groupId).leaderOrNull)
- assertEquals(3, getGroup(groupId).generationId)
- assertGroupState(groupState = Empty)
- }
-
- @Test
- def testLeaderRejoinBeforeFinalRebalanceTimeoutWithLongSessionTimeout(): Unit = {
- groupStuckInRebalanceTimeoutDueToNonjoinedStaticMember()
-
- // The static leader should be back now, moving group towards CompletingRebalance
- val leaderRejoinGroupResult = staticJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, leaderInstanceId, protocolType, protocols)
- checkJoinGroupResult(leaderRejoinGroupResult,
- Errors.NONE,
- 3,
- Set(leaderInstanceId),
- CompletingRebalance,
- Some(protocolType)
- )
- assertEquals(Set(leaderRejoinGroupResult.memberId), getGroup(groupId).allMembers)
- assertNotNull(getGroup(groupId).leaderOrNull)
- assertEquals(3, getGroup(groupId).generationId)
- }
-
- def groupStuckInRebalanceTimeoutDueToNonjoinedStaticMember(): Unit = {
- val longSessionTimeout = DefaultSessionTimeout * 2
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId, sessionTimeout = longSessionTimeout)
-
- val dynamicJoinFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocolSuperset, sessionTimeout = longSessionTimeout)
- timer.advanceClock(DefaultRebalanceTimeout + 1)
-
- val dynamicJoinResult = await(dynamicJoinFuture, 100)
- // The new dynamic member has been elected as leader
- assertEquals(dynamicJoinResult.leaderId, dynamicJoinResult.memberId)
- assertEquals(Errors.NONE, dynamicJoinResult.error)
- assertEquals(3, dynamicJoinResult.members.size)
- assertEquals(2, dynamicJoinResult.generationId)
- assertGroupState(groupState = CompletingRebalance)
-
- assertEquals(Set(rebalanceResult.leaderId, rebalanceResult.followerId,
- dynamicJoinResult.memberId), getGroup(groupId).allMembers)
- assertEquals(Set(leaderInstanceId, followerInstanceId),
- getGroup(groupId).allStaticMembers)
- assertEquals(Set(dynamicJoinResult.memberId), getGroup(groupId).allDynamicMembers)
-
- // Send a special leave group request from static follower, moving group towards PreparingRebalance
- val followerLeaveGroupResults = singleLeaveGroup(groupId, rebalanceResult.followerId)
- verifyLeaveGroupResult(followerLeaveGroupResults)
- assertGroupState(groupState = PreparingRebalance)
-
- timer.advanceClock(DefaultRebalanceTimeout + 1)
- // Only static leader is maintained, and group is stuck at PreparingRebalance stage
- assertTrue(getGroup(groupId).allDynamicMembers.isEmpty)
- assertEquals(Set(rebalanceResult.leaderId), getGroup(groupId).allMembers)
- assertTrue(getGroup(groupId).allDynamicMembers.isEmpty)
- assertEquals(2, getGroup(groupId).generationId)
- assertGroupState(groupState = PreparingRebalance)
- }
-
- @Test
- def testStaticMemberFollowerFailToRejoinBeforeRebalanceTimeout(): Unit = {
- // Increase session timeout so that the follower won't be evicted when rebalance timeout is reached.
- val initialRebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId, sessionTimeout = DefaultRebalanceTimeout * 2)
-
- val newMemberInstanceId = "newMember"
-
- val leaderId = initialRebalanceResult.leaderId
-
- val newMemberJoinGroupFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType,
- protocolSuperset, Some(newMemberInstanceId))
- assertGroupState(groupState = PreparingRebalance)
-
- val leaderRejoinGroupResult = staticJoinGroup(groupId, leaderId, leaderInstanceId, protocolType, protocolSuperset, clockAdvance = DefaultRebalanceTimeout + 1)
- checkJoinGroupResult(leaderRejoinGroupResult,
- Errors.NONE,
- initialRebalanceResult.generation + 1,
- Set(leaderInstanceId, followerInstanceId, newMemberInstanceId),
- CompletingRebalance,
- Some(protocolType),
- expectedLeaderId = leaderId,
- expectedMemberId = leaderId)
-
- val newMemberJoinGroupResult = Await.result(newMemberJoinGroupFuture, Duration(1, TimeUnit.MILLISECONDS))
- assertEquals(Errors.NONE, newMemberJoinGroupResult.error)
- checkJoinGroupResult(newMemberJoinGroupResult,
- Errors.NONE,
- initialRebalanceResult.generation + 1,
- Set.empty,
- CompletingRebalance,
- Some(protocolType),
- expectedLeaderId = leaderId)
- }
-
- @Test
- def testStaticMemberLeaderFailToRejoinBeforeRebalanceTimeout(): Unit = {
- // Increase session timeout so that the leader won't be evicted when rebalance timeout is reached.
- val initialRebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId, sessionTimeout = DefaultRebalanceTimeout * 2)
-
- val newMemberInstanceId = "newMember"
-
- val newMemberJoinGroupFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType,
- protocolSuperset, Some(newMemberInstanceId))
- timer.advanceClock(1)
- assertGroupState(groupState = PreparingRebalance)
-
- val oldFollowerRejoinGroupResult = staticJoinGroup(groupId, initialRebalanceResult.followerId, followerInstanceId, protocolType, protocolSuperset, clockAdvance = DefaultRebalanceTimeout + 1)
- val newMemberJoinGroupResult = Await.result(newMemberJoinGroupFuture, Duration(1, TimeUnit.MILLISECONDS))
-
- val (newLeaderResult, newFollowerResult) = if (oldFollowerRejoinGroupResult.leaderId == oldFollowerRejoinGroupResult.memberId)
- (oldFollowerRejoinGroupResult, newMemberJoinGroupResult)
- else
- (newMemberJoinGroupResult, oldFollowerRejoinGroupResult)
-
- checkJoinGroupResult(newLeaderResult,
- Errors.NONE,
- initialRebalanceResult.generation + 1,
- Set(leaderInstanceId, followerInstanceId, newMemberInstanceId),
- CompletingRebalance,
- Some(protocolType))
-
- checkJoinGroupResult(newFollowerResult,
- Errors.NONE,
- initialRebalanceResult.generation + 1,
- Set.empty,
- CompletingRebalance,
- Some(protocolType),
- expectedLeaderId = newLeaderResult.memberId)
- }
-
- @Test
- def testJoinGroupProtocolTypeIsNotProvidedWhenAnErrorOccurs(): Unit = {
- // JoinGroup(leader)
- val leaderResponseFuture = sendJoinGroup(groupId, "fake-id", protocolType,
- protocolSuperset, Some(leaderInstanceId), DefaultSessionTimeout)
-
- // The Protocol Type is None when there is an error
- val leaderJoinGroupResult = await(leaderResponseFuture, 1)
- assertEquals(Errors.UNKNOWN_MEMBER_ID, leaderJoinGroupResult.error)
- assertEquals(None, leaderJoinGroupResult.protocolType)
- }
-
- @Test
- def testJoinGroupReturnsTheProtocolType(): Unit = {
- // JoinGroup(leader)
- val leaderResponseFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType,
- protocolSuperset, Some(leaderInstanceId), DefaultSessionTimeout)
-
- // JoinGroup(follower)
- val followerResponseFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType,
- protocolSuperset, Some(followerInstanceId), DefaultSessionTimeout)
-
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
- timer.advanceClock(DefaultRebalanceTimeout + 1)
-
- // The Protocol Type is Defined when there is not error
- val leaderJoinGroupResult = await(leaderResponseFuture, 1)
- assertEquals(Errors.NONE, leaderJoinGroupResult.error)
- assertEquals(protocolType, leaderJoinGroupResult.protocolType.orNull)
-
- // The Protocol Type is Defined when there is not error
- val followerJoinGroupResult = await(followerResponseFuture, 1)
- assertEquals(Errors.NONE, followerJoinGroupResult.error)
- assertEquals(protocolType, followerJoinGroupResult.protocolType.orNull)
- }
-
- @Test
- def testSyncGroupReturnsAnErrorWhenProtocolTypeIsInconsistent(): Unit = {
- testSyncGroupProtocolTypeAndNameWith(Some("whatever"), None, Errors.INCONSISTENT_GROUP_PROTOCOL,
- None, None)
- }
-
- @Test
- def testSyncGroupReturnsAnErrorWhenProtocolNameIsInconsistent(): Unit = {
- testSyncGroupProtocolTypeAndNameWith(None, Some("whatever"), Errors.INCONSISTENT_GROUP_PROTOCOL,
- None, None)
- }
-
- @Test
- def testSyncGroupSucceedWhenProtocolTypeAndNameAreNotProvided(): Unit = {
- testSyncGroupProtocolTypeAndNameWith(None, None, Errors.NONE,
- Some(protocolType), Some(protocolName))
- }
-
- @Test
- def testSyncGroupSucceedWhenProtocolTypeAndNameAreConsistent(): Unit = {
- testSyncGroupProtocolTypeAndNameWith(Some(protocolType), Some(protocolName),
- Errors.NONE, Some(protocolType), Some(protocolName))
- }
-
- private def testSyncGroupProtocolTypeAndNameWith(protocolType: Option[String],
- protocolName: Option[String],
- expectedError: Errors,
- expectedProtocolType: Option[String],
- expectedProtocolName: Option[String]): Unit = {
- // JoinGroup(leader) with the Protocol Type of the group
- val leaderResponseFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, this.protocolType,
- protocolSuperset, Some(leaderInstanceId), DefaultSessionTimeout)
-
- // JoinGroup(follower) with the Protocol Type of the group
- val followerResponseFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, this.protocolType,
- protocolSuperset, Some(followerInstanceId), DefaultSessionTimeout)
-
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
- timer.advanceClock(DefaultRebalanceTimeout + 1)
-
- val leaderJoinGroupResult = await(leaderResponseFuture, 1)
- val leaderId = leaderJoinGroupResult.memberId
- val generationId = leaderJoinGroupResult.generationId
- val followerJoinGroupResult = await(followerResponseFuture, 1)
- val followerId = followerJoinGroupResult.memberId
-
- // SyncGroup with the provided Protocol Type and Name
- val leaderSyncGroupResult = syncGroupLeader(groupId, generationId, leaderId,
- Map(leaderId -> Array.empty), protocolType, protocolName)
- assertEquals(expectedError, leaderSyncGroupResult.error)
- assertEquals(expectedProtocolType, leaderSyncGroupResult.protocolType)
- assertEquals(expectedProtocolName, leaderSyncGroupResult.protocolName)
-
- // SyncGroup with the provided Protocol Type and Name
- val followerSyncGroupResult = syncGroupFollower(groupId, generationId, followerId,
- protocolType, protocolName)
- assertEquals(expectedError, followerSyncGroupResult.error)
- assertEquals(expectedProtocolType, followerSyncGroupResult.protocolType)
- assertEquals(expectedProtocolName, followerSyncGroupResult.protocolName)
- }
-
- private class RebalanceResult(val generation: Int,
- val leaderId: String,
- val leaderAssignment: Array[Byte],
- val followerId: String,
- val followerAssignment: Array[Byte])
- /**
- * Generate static member rebalance results, including:
- * - generation
- * - leader id
- * - leader assignment
- * - follower id
- * - follower assignment
- */
- private def staticMembersJoinAndRebalance(leaderInstanceId: String,
- followerInstanceId: String,
- sessionTimeout: Int = DefaultSessionTimeout,
- rebalanceTimeout: Int = DefaultRebalanceTimeout): RebalanceResult = {
- val leaderResponseFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType,
- protocolSuperset, Some(leaderInstanceId), sessionTimeout, rebalanceTimeout)
-
- val followerResponseFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType,
- protocolSuperset, Some(followerInstanceId), sessionTimeout, rebalanceTimeout)
- // The goal for two timer advance is to let first group initial join complete and set newMemberAdded flag to false. Next advance is
- // to trigger the rebalance as needed for follower delayed join. One large time advance won't help because we could only populate one
- // delayed join from purgatory and the new delayed op is created at that time and never be triggered.
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
- timer.advanceClock(DefaultRebalanceTimeout + 1)
- val newGeneration = 1
-
- val leaderJoinGroupResult = await(leaderResponseFuture, 1)
- assertEquals(Errors.NONE, leaderJoinGroupResult.error)
- assertEquals(newGeneration, leaderJoinGroupResult.generationId)
-
- val followerJoinGroupResult = await(followerResponseFuture, 1)
- assertEquals(Errors.NONE, followerJoinGroupResult.error)
- assertEquals(newGeneration, followerJoinGroupResult.generationId)
-
- val leaderId = leaderJoinGroupResult.memberId
- when(replicaManager.onlinePartition(any[TopicPartition])).thenReturn(Some(mock(classOf[Partition])))
- val leaderSyncGroupResult = syncGroupLeader(groupId, leaderJoinGroupResult.generationId, leaderId, Map(leaderId -> Array[Byte]()))
- assertEquals(Errors.NONE, leaderSyncGroupResult.error)
- assertTrue(getGroup(groupId).is(Stable))
-
- val followerId = followerJoinGroupResult.memberId
- val followerSyncGroupResult = syncGroupFollower(groupId, leaderJoinGroupResult.generationId, followerId)
- assertEquals(Errors.NONE, followerSyncGroupResult.error)
- assertTrue(getGroup(groupId).is(Stable))
-
- new RebalanceResult(newGeneration,
- leaderId,
- leaderSyncGroupResult.memberAssignment,
- followerId,
- followerSyncGroupResult.memberAssignment)
- }
-
- private def checkJoinGroupResult(joinGroupResult: JoinGroupResult,
- expectedError: Errors,
- expectedGeneration: Int,
- expectedGroupInstanceIds: Set[String],
- expectedGroupState: GroupState,
- expectedProtocolType: Option[String],
- expectedLeaderId: String = JoinGroupRequest.UNKNOWN_MEMBER_ID,
- expectedMemberId: String = JoinGroupRequest.UNKNOWN_MEMBER_ID,
- expectedSkipAssignment: Boolean = false): Unit = {
- assertEquals(expectedError, joinGroupResult.error)
- assertEquals(expectedGeneration, joinGroupResult.generationId)
- assertEquals(expectedGroupInstanceIds.size, joinGroupResult.members.size)
- val resultedGroupInstanceIds = joinGroupResult.members.map(member => member.groupInstanceId).toSet
- assertEquals(expectedGroupInstanceIds, resultedGroupInstanceIds)
- assertGroupState(groupState = expectedGroupState)
- assertEquals(expectedProtocolType, joinGroupResult.protocolType)
- assertEquals(expectedSkipAssignment, joinGroupResult.skipAssignment)
-
- if (!expectedLeaderId.equals(JoinGroupRequest.UNKNOWN_MEMBER_ID)) {
- assertEquals(expectedLeaderId, joinGroupResult.leaderId)
- }
- if (!expectedMemberId.equals(JoinGroupRequest.UNKNOWN_MEMBER_ID)) {
- assertEquals(expectedMemberId, joinGroupResult.memberId)
- }
- }
-
- @Test
- def testHeartbeatWrongCoordinator(): Unit = {
- val heartbeatResult = heartbeat(otherGroupId, memberId, -1)
- assertEquals(Errors.NOT_COORDINATOR, heartbeatResult)
- }
-
- @Test
- def testHeartbeatUnknownGroup(): Unit = {
- val heartbeatResult = heartbeat(groupId, memberId, -1)
- assertEquals(Errors.UNKNOWN_MEMBER_ID, heartbeatResult)
- }
-
- @Test
- def testHeartbeatDeadGroup(): Unit = {
- val memberId = "memberId"
-
- val deadGroupId = "deadGroupId"
-
- groupCoordinator.groupManager.addGroup(new GroupMetadata(deadGroupId, Dead, new MockTime()))
- val heartbeatResult = heartbeat(deadGroupId, memberId, 1)
- assertEquals(Errors.COORDINATOR_NOT_AVAILABLE, heartbeatResult)
- }
-
- @Test
- def testHeartbeatEmptyGroup(): Unit = {
- val memberId = "memberId"
-
- val group = new GroupMetadata(groupId, Empty, new MockTime())
- val member = new MemberMetadata(memberId, Some(groupInstanceId),
- ClientId, ClientHost, DefaultRebalanceTimeout, DefaultSessionTimeout,
- protocolType, List(("range", Array.empty[Byte]), ("roundrobin", Array.empty[Byte])))
-
- group.add(member)
- groupCoordinator.groupManager.addGroup(group)
- val heartbeatResult = heartbeat(groupId, memberId, 0)
- assertEquals(Errors.UNKNOWN_MEMBER_ID, heartbeatResult)
- }
-
- @Test
- def testHeartbeatUnknownConsumerExistingGroup(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val otherMemberId = "memberId"
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedMemberId = joinGroupResult.memberId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val syncGroupResult = syncGroupLeader(groupId, joinGroupResult.generationId, assignedMemberId, Map(assignedMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- val heartbeatResult = heartbeat(groupId, otherMemberId, 1)
- assertEquals(Errors.UNKNOWN_MEMBER_ID, heartbeatResult)
- }
-
- @Test
- def testHeartbeatRebalanceInProgress(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedMemberId = joinGroupResult.memberId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val heartbeatResult = heartbeat(groupId, assignedMemberId, 1)
- assertEquals(Errors.NONE, heartbeatResult)
- }
-
- @Test
- def testHeartbeatIllegalGeneration(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedMemberId = joinGroupResult.memberId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val syncGroupResult = syncGroupLeader(groupId, joinGroupResult.generationId, assignedMemberId, Map(assignedMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- val heartbeatResult = heartbeat(groupId, assignedMemberId, 2)
- assertEquals(Errors.ILLEGAL_GENERATION, heartbeatResult)
- }
-
- @Test
- def testValidHeartbeat(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedConsumerId = joinGroupResult.memberId
- val generationId = joinGroupResult.generationId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val syncGroupResult = syncGroupLeader(groupId, generationId, assignedConsumerId, Map(assignedConsumerId -> Array[Byte]()))
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- val heartbeatResult = heartbeat(groupId, assignedConsumerId, 1)
- assertEquals(Errors.NONE, heartbeatResult)
- }
-
- @Test
- def testSessionTimeout(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedConsumerId = joinGroupResult.memberId
- val generationId = joinGroupResult.generationId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val syncGroupResult = syncGroupLeader(groupId, generationId, assignedConsumerId, Map(assignedConsumerId -> Array[Byte]()))
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- when(replicaManager.getPartition(new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, groupPartitionId)))
- .thenReturn(HostedPartition.None)
-
- timer.advanceClock(DefaultSessionTimeout + 100)
-
- val heartbeatResult = heartbeat(groupId, assignedConsumerId, 1)
- assertEquals(Errors.UNKNOWN_MEMBER_ID, heartbeatResult)
- }
-
- @Test
- def testHeartbeatMaintainsSession(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val sessionTimeout = 1000
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols,
- rebalanceTimeout = sessionTimeout, sessionTimeout = sessionTimeout)
- val assignedConsumerId = joinGroupResult.memberId
- val generationId = joinGroupResult.generationId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val syncGroupResult = syncGroupLeader(groupId, generationId, assignedConsumerId, Map(assignedConsumerId -> Array[Byte]()))
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- timer.advanceClock(sessionTimeout / 2)
-
- var heartbeatResult = heartbeat(groupId, assignedConsumerId, 1)
- assertEquals(Errors.NONE, heartbeatResult)
-
- timer.advanceClock(sessionTimeout / 2 + 100)
-
- heartbeatResult = heartbeat(groupId, assignedConsumerId, 1)
- assertEquals(Errors.NONE, heartbeatResult)
- }
-
- @Test
- def testCommitMaintainsSession(): Unit = {
- val sessionTimeout = 1000
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols,
- rebalanceTimeout = sessionTimeout, sessionTimeout = sessionTimeout)
- val assignedMemberId = joinGroupResult.memberId
- val generationId = joinGroupResult.generationId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val syncGroupResult = syncGroupLeader(groupId, generationId, assignedMemberId, Map(assignedMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- timer.advanceClock(sessionTimeout / 2)
-
- val commitOffsetResult = commitOffsets(groupId, assignedMemberId, generationId, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.NONE), commitOffsetResult)
-
- timer.advanceClock(sessionTimeout / 2 + 100)
-
- val heartbeatResult = heartbeat(groupId, assignedMemberId, 1)
- assertEquals(Errors.NONE, heartbeatResult)
- }
-
- @Test
- def testSessionTimeoutDuringRebalance(): Unit = {
- // create a group with a single member
- val firstJoinResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols,
- rebalanceTimeout = 2000, sessionTimeout = 1000)
- val firstMemberId = firstJoinResult.memberId
- val firstGenerationId = firstJoinResult.generationId
- assertEquals(firstMemberId, firstJoinResult.leaderId)
- assertEquals(Errors.NONE, firstJoinResult.error)
-
- val firstSyncResult = syncGroupLeader(groupId, firstGenerationId, firstMemberId, Map(firstMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, firstSyncResult.error)
-
- // now have a new member join to trigger a rebalance
- val otherJoinFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
-
- timer.advanceClock(500)
-
- var heartbeatResult = heartbeat(groupId, firstMemberId, firstGenerationId)
- assertEquals(Errors.REBALANCE_IN_PROGRESS, heartbeatResult)
-
- // letting the session expire should make the member fall out of the group
- timer.advanceClock(1100)
-
- heartbeatResult = heartbeat(groupId, firstMemberId, firstGenerationId)
- assertEquals(Errors.UNKNOWN_MEMBER_ID, heartbeatResult)
-
- // and the rebalance should complete with only the new member
- val otherJoinResult = await(otherJoinFuture, DefaultSessionTimeout+100)
- assertEquals(Errors.NONE, otherJoinResult.error)
- }
-
- @Test
- def testRebalanceCompletesBeforeMemberJoins(): Unit = {
- // create a group with a single member
- val firstJoinResult = staticJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, leaderInstanceId, protocolType, protocols,
- rebalanceTimeout = 1200, sessionTimeout = 1000)
- val firstMemberId = firstJoinResult.memberId
- val firstGenerationId = firstJoinResult.generationId
- assertEquals(firstMemberId, firstJoinResult.leaderId)
- assertEquals(Errors.NONE, firstJoinResult.error)
-
- val firstSyncResult = syncGroupLeader(groupId, firstGenerationId, firstMemberId, Map(firstMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, firstSyncResult.error)
-
- // now have a new member join to trigger a rebalance
- val otherMemberSessionTimeout = DefaultSessionTimeout
- val otherJoinFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
-
- // send a couple heartbeats to keep the member alive while the rebalance finishes
- var expectedResultList = List(Errors.REBALANCE_IN_PROGRESS, Errors.REBALANCE_IN_PROGRESS)
- for (expectedResult <- expectedResultList) {
- timer.advanceClock(otherMemberSessionTimeout)
- val heartbeatResult = heartbeat(groupId, firstMemberId, firstGenerationId)
- assertEquals(expectedResult, heartbeatResult)
- }
-
- // now timeout the rebalance
- timer.advanceClock(otherMemberSessionTimeout)
- val otherJoinResult = await(otherJoinFuture, otherMemberSessionTimeout+100)
- val otherMemberId = otherJoinResult.memberId
- val otherGenerationId = otherJoinResult.generationId
- val syncResult = syncGroupLeader(groupId, otherGenerationId, otherMemberId, Map(otherMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, syncResult.error)
-
- // the unjoined static member should be remained in the group before session timeout.
- assertEquals(Errors.NONE, otherJoinResult.error)
- var heartbeatResult = heartbeat(groupId, firstMemberId, firstGenerationId)
- assertEquals(Errors.ILLEGAL_GENERATION, heartbeatResult)
-
- expectedResultList = List(Errors.NONE, Errors.NONE, Errors.REBALANCE_IN_PROGRESS)
-
- // now session timeout the unjoined member. Still keeping the new member.
- for (expectedResult <- expectedResultList) {
- timer.advanceClock(otherMemberSessionTimeout)
- heartbeatResult = heartbeat(groupId, otherMemberId, otherGenerationId)
- assertEquals(expectedResult, heartbeatResult)
- }
-
- val otherRejoinGroupFuture = sendJoinGroup(groupId, otherMemberId, protocolType, protocols)
- val otherReJoinResult = await(otherRejoinGroupFuture, otherMemberSessionTimeout+100)
- assertEquals(Errors.NONE, otherReJoinResult.error)
-
- val otherRejoinGenerationId = otherReJoinResult.generationId
- val reSyncResult = syncGroupLeader(groupId, otherRejoinGenerationId, otherMemberId, Map(otherMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, reSyncResult.error)
-
- // the joined member should get heart beat response with no error. Let the new member keep heartbeating for a while
- // to verify that no new rebalance is triggered unexpectedly
- for ( _ <- 1 to 20) {
- timer.advanceClock(500)
- heartbeatResult = heartbeat(groupId, otherMemberId, otherRejoinGenerationId)
- assertEquals(Errors.NONE, heartbeatResult)
- }
- }
-
- @Test
- def testSyncGroupEmptyAssignment(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedConsumerId = joinGroupResult.memberId
- val generationId = joinGroupResult.generationId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val syncGroupResult = syncGroupLeader(groupId, generationId, assignedConsumerId, Map())
- assertEquals(Errors.NONE, syncGroupResult.error)
- assertTrue(syncGroupResult.memberAssignment.isEmpty)
-
- val heartbeatResult = heartbeat(groupId, assignedConsumerId, 1)
- assertEquals(Errors.NONE, heartbeatResult)
- }
-
- @Test
- def testSyncGroupNotCoordinator(): Unit = {
- val generation = 1
-
- val syncGroupResult = syncGroupFollower(otherGroupId, generation, memberId)
- assertEquals(Errors.NOT_COORDINATOR, syncGroupResult.error)
- }
-
- @Test
- def testSyncGroupFromUnknownGroup(): Unit = {
- val syncGroupResult = syncGroupFollower(groupId, 1, memberId)
- assertEquals(Errors.UNKNOWN_MEMBER_ID, syncGroupResult.error)
- }
-
- @Test
- def testSyncGroupFromUnknownMember(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedConsumerId = joinGroupResult.memberId
- val generationId = joinGroupResult.generationId
- assertEquals(Errors.NONE, joinGroupResult.error)
-
- val syncGroupResult = syncGroupLeader(groupId, generationId, assignedConsumerId, Map(assignedConsumerId -> Array[Byte]()))
- val syncGroupError = syncGroupResult.error
- assertEquals(Errors.NONE, syncGroupError)
-
- val unknownMemberId = "blah"
- val unknownMemberSyncResult = syncGroupFollower(groupId, generationId, unknownMemberId)
- assertEquals(Errors.UNKNOWN_MEMBER_ID, unknownMemberSyncResult.error)
- }
-
- @Test
- def testSyncGroupFromIllegalGeneration(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedConsumerId = joinGroupResult.memberId
- val generationId = joinGroupResult.generationId
- assertEquals(Errors.NONE, joinGroupResult.error)
-
- // send the sync group with an invalid generation
- val syncGroupResult = syncGroupLeader(groupId, generationId+1, assignedConsumerId, Map(assignedConsumerId -> Array[Byte]()))
- assertEquals(Errors.ILLEGAL_GENERATION, syncGroupResult.error)
- }
-
- @Test
- def testJoinGroupFromUnchangedFollowerDoesNotRebalance(): Unit = {
- // to get a group of two members:
- // 1. join and sync with a single member (because we can't immediately join with two members)
- // 2. join and sync with the first member and a new member
-
- val firstJoinResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val firstMemberId = firstJoinResult.memberId
- val firstGenerationId = firstJoinResult.generationId
- assertEquals(firstMemberId, firstJoinResult.leaderId)
- assertEquals(Errors.NONE, firstJoinResult.error)
-
- val firstSyncResult = syncGroupLeader(groupId, firstGenerationId, firstMemberId, Map(firstMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, firstSyncResult.error)
-
- val otherJoinFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
-
- val joinFuture = sendJoinGroup(groupId, firstMemberId, protocolType, protocols)
-
- val joinResult = await(joinFuture, DefaultSessionTimeout+100)
- val otherJoinResult = await(otherJoinFuture, DefaultSessionTimeout+100)
- assertEquals(Errors.NONE, joinResult.error)
- assertEquals(Errors.NONE, otherJoinResult.error)
- assertTrue(joinResult.generationId == otherJoinResult.generationId)
-
- assertEquals(firstMemberId, joinResult.leaderId)
- assertEquals(firstMemberId, otherJoinResult.leaderId)
-
- val nextGenerationId = joinResult.generationId
-
- // this shouldn't cause a rebalance since protocol information hasn't changed
- val followerJoinResult = await(sendJoinGroup(groupId, otherJoinResult.memberId, protocolType, protocols), 1)
-
- assertEquals(Errors.NONE, followerJoinResult.error)
- assertEquals(nextGenerationId, followerJoinResult.generationId)
- }
-
- @Test
- def testJoinGroupFromUnchangedLeaderShouldRebalance(): Unit = {
- val firstJoinResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val firstMemberId = firstJoinResult.memberId
- val firstGenerationId = firstJoinResult.generationId
- assertEquals(firstMemberId, firstJoinResult.leaderId)
- assertEquals(Errors.NONE, firstJoinResult.error)
-
- val firstSyncResult = syncGroupLeader(groupId, firstGenerationId, firstMemberId, Map(firstMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, firstSyncResult.error)
-
- // join groups from the leader should force the group to rebalance, which allows the
- // leader to push new assignments when local metadata changes
-
- val secondJoinResult = await(sendJoinGroup(groupId, firstMemberId, protocolType, protocols), 1)
-
- assertEquals(Errors.NONE, secondJoinResult.error)
- assertNotEquals(firstGenerationId, secondJoinResult.generationId)
- }
-
- /**
- * Test if the following scenario completes a rebalance correctly: A new member starts a JoinGroup request with
- * an UNKNOWN_MEMBER_ID, attempting to join a stable group. But never initiates the second JoinGroup request with
- * the provided member ID and times out. The test checks if original member remains the sole member in this group,
- * which should remain stable throughout this test.
- */
- @Test
- def testSecondMemberPartiallyJoinAndTimeout(): Unit = {
- val firstJoinResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val firstMemberId = firstJoinResult.memberId
- val firstGenerationId = firstJoinResult.generationId
- assertEquals(firstMemberId, firstJoinResult.leaderId)
- assertEquals(Errors.NONE, firstJoinResult.error)
-
- // Starting sync group leader
- val firstSyncResult = syncGroupLeader(groupId, firstGenerationId, firstMemberId, Map(firstMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, firstSyncResult.error)
- timer.advanceClock(100)
- assertEquals(Set(firstMemberId), groupCoordinator.groupManager.getGroup(groupId).get.allMembers)
- assertEquals(groupCoordinator.groupManager.getGroup(groupId).get.allMembers,
- groupCoordinator.groupManager.getGroup(groupId).get.allDynamicMembers)
- assertEquals(0, groupCoordinator.groupManager.getGroup(groupId).get.numPending)
- val group = groupCoordinator.groupManager.getGroup(groupId).get
-
- // ensure the group is stable before a new member initiates join request
- assertEquals(Stable, group.currentState)
-
- // new member initiates join group
- val secondJoinResult = joinGroupPartial(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- assertEquals(Errors.MEMBER_ID_REQUIRED, secondJoinResult.error)
- assertEquals(1, group.numPending)
- assertEquals(Stable, group.currentState)
-
- // advance clock to timeout the pending member
- assertEquals(Set(firstMemberId), group.allMembers)
- assertEquals(1, group.numPending)
- timer.advanceClock(300)
-
- // original (firstMember) member sends heartbeats to prevent session timeouts.
- val heartbeatResult = heartbeat(groupId, firstMemberId, 1)
- assertEquals(Errors.NONE, heartbeatResult)
-
- // timeout the pending member
- timer.advanceClock(300)
-
- // at this point the second member should have been removed from pending list (session timeout),
- // and the group should be in Stable state with only the first member in it.
- assertEquals(Set(firstMemberId), group.allMembers)
- assertEquals(0, group.numPending)
- assertEquals(Stable, group.currentState)
- assertTrue(group.has(firstMemberId))
- }
-
- /**
- * Create a group with two members in Stable state. Create a third pending member by completing it's first JoinGroup
- * request without a member id.
- */
- private def setupGroupWithPendingMember(): JoinGroupResult = {
- // add the first member
- val joinResult1 = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- assertGroupState(groupState = CompletingRebalance)
-
- // now the group is stable, with the one member that joined above
- val firstSyncResult = syncGroupLeader(groupId, joinResult1.generationId, joinResult1.memberId, Map(joinResult1.memberId -> Array[Byte]()))
- assertEquals(Errors.NONE, firstSyncResult.error)
- assertGroupState(groupState = Stable)
-
- // start the join for the second member
- val secondJoinFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
-
- // rejoin the first member back into the group
- val firstJoinFuture = sendJoinGroup(groupId, joinResult1.memberId, protocolType, protocols)
- val firstMemberJoinResult = await(firstJoinFuture, DefaultSessionTimeout+100)
- val secondMemberJoinResult = await(secondJoinFuture, DefaultSessionTimeout+100)
- assertGroupState(groupState = CompletingRebalance)
-
- // stabilize the group
- val secondSyncResult = syncGroupLeader(groupId, firstMemberJoinResult.generationId, joinResult1.memberId, Map(joinResult1.memberId -> Array[Byte]()))
- assertEquals(Errors.NONE, secondSyncResult.error)
- assertGroupState(groupState = Stable)
-
- // re-join an existing member, to transition the group to PreparingRebalance state.
- sendJoinGroup(groupId, firstMemberJoinResult.memberId, protocolType, protocols)
- assertGroupState(groupState = PreparingRebalance)
-
- // create a pending member in the group
- val pendingMember = joinGroupPartial(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols, sessionTimeout=100)
- assertEquals(1, groupCoordinator.groupManager.getGroup(groupId).get.numPending)
-
- // re-join the second existing member
- sendJoinGroup(groupId, secondMemberJoinResult.memberId, protocolType, protocols)
- assertGroupState(groupState = PreparingRebalance)
- assertEquals(1, groupCoordinator.groupManager.getGroup(groupId).get.numPending)
-
- pendingMember
- }
-
- /**
- * Setup a group in with a pending member. The test checks if the a pending member joining completes the rebalancing
- * operation
- */
- @Test
- def testJoinGroupCompletionWhenPendingMemberJoins(): Unit = {
- val pendingMember = setupGroupWithPendingMember()
-
- // compete join group for the pending member
- val pendingMemberJoinFuture = sendJoinGroup(groupId, pendingMember.memberId, protocolType, protocols)
- await(pendingMemberJoinFuture, DefaultSessionTimeout+100)
-
- assertGroupState(groupState = CompletingRebalance)
- assertEquals(3, group().allMembers.size)
- assertEquals(0, group().numPending)
- }
-
- /**
- * Setup a group in with a pending member. The test checks if the timeout of the pending member will
- * cause the group to return to a CompletingRebalance state.
- */
- @Test
- def testJoinGroupCompletionWhenPendingMemberTimesOut(): Unit = {
- setupGroupWithPendingMember()
-
- // Advancing Clock by > 100 (session timeout for third and fourth member)
- // and < 500 (for first and second members). This will force the coordinator to attempt join
- // completion on heartbeat expiration (since we are in PendingRebalance stage).
- timer.advanceClock(120)
-
- assertGroupState(groupState = CompletingRebalance)
- assertEquals(2, group().allMembers.size)
- assertEquals(0, group().numPending)
- }
-
- @Test
- def testPendingMembersLeavesGroup(): Unit = {
- val pending = setupGroupWithPendingMember()
-
- val leaveGroupResults = singleLeaveGroup(groupId, pending.memberId)
- verifyLeaveGroupResult(leaveGroupResults)
-
- assertGroupState(groupState = CompletingRebalance)
- assertEquals(2, group().allMembers.size)
- assertEquals(2, group().allDynamicMembers.size)
- assertEquals(0, group().numPending)
- }
-
- private def verifyHeartbeat(
- joinGroupResult: JoinGroupResult,
- expectedError: Errors
- ): Unit = {
- val heartbeatResult = heartbeat(
- groupId,
- joinGroupResult.memberId,
- joinGroupResult.generationId
- )
- assertEquals(expectedError, heartbeatResult)
- }
-
- private def joinWithNMembers(nbMembers: Int): Seq[JoinGroupResult] = {
- val requiredKnownMemberId = true
-
- // First JoinRequests
- var futures = 1.to(nbMembers).map { _ =>
- sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols,
- None, DefaultSessionTimeout, DefaultRebalanceTimeout, requiredKnownMemberId)
- }
-
- // Get back the assigned member ids
- val memberIds = futures.map(await(_, 1).memberId)
-
- // Second JoinRequests
- futures = memberIds.map { memberId =>
- sendJoinGroup(groupId, memberId, protocolType, protocols,
- None, DefaultSessionTimeout, DefaultRebalanceTimeout, requiredKnownMemberId)
- }
-
- timer.advanceClock(GroupInitialRebalanceDelay + 1)
- timer.advanceClock(DefaultRebalanceTimeout + 1)
-
- futures.map(await(_, 1))
- }
-
- @Test
- def testRebalanceTimesOutWhenSyncRequestIsNotReceived(): Unit = {
- // This test case ensure that the DelayedSync does kick out all members
- // if they don't sent a sync request before the rebalance timeout. The
- // group is in the Stable state in this case.
- val results = joinWithNMembers(nbMembers = 3)
- assertEquals(Set(Errors.NONE), results.map(_.error).toSet)
-
- // Advance time
- timer.advanceClock(DefaultRebalanceTimeout / 2)
-
- // Heartbeats to ensure that heartbeating does not interfere with the
- // delayed sync operation.
- results.foreach { joinGroupResult =>
- verifyHeartbeat(joinGroupResult, Errors.NONE)
- }
-
- // Advance part the rebalance timeout to trigger the delayed operation.
- when(replicaManager.onlinePartition(any[TopicPartition]))
- .thenReturn(Some(mock(classOf[Partition])))
-
- timer.advanceClock(DefaultRebalanceTimeout / 2 + 1)
-
- // Heartbeats fail because none of the members have sent the sync request
- results.foreach { joinGroupResult =>
- verifyHeartbeat(joinGroupResult, Errors.UNKNOWN_MEMBER_ID)
- }
- }
-
- @Test
- def testRebalanceTimesOutWhenSyncRequestIsNotReceivedFromFollowers(): Unit = {
- // This test case ensure that the DelayedSync does kick out the followers
- // if they don't sent a sync request before the rebalance timeout. The
- // group is in the Stable state in this case.
- val results = joinWithNMembers(nbMembers = 3)
- assertEquals(Set(Errors.NONE), results.map(_.error).toSet)
-
- // Advance time
- timer.advanceClock(DefaultRebalanceTimeout / 2)
-
- // Heartbeats to ensure that heartbeating does not interfere with the
- // delayed sync operation.
- results.foreach { joinGroupResult =>
- verifyHeartbeat(joinGroupResult, Errors.NONE)
- }
-
- // Leader sends Sync
- val assignments = results.map(result => result.memberId -> Array.empty[Byte]).toMap
- val leaderResult = sendSyncGroupLeader(groupId, results.head.generationId, results.head.memberId,
- Some(protocolType), Some(protocolName), None, assignments)
-
- assertEquals(Errors.NONE, await(leaderResult, 1).error)
-
- // Leader should be able to heartbeat
- verifyHeartbeat(results.head, Errors.NONE)
-
- // Advance part the rebalance timeout to trigger the delayed operation.
- timer.advanceClock(DefaultRebalanceTimeout / 2 + 1)
-
- // Leader should be able to heartbeat
- verifyHeartbeat(results.head, Errors.REBALANCE_IN_PROGRESS)
-
- // Followers should have been removed.
- results.tail.foreach { joinGroupResult =>
- verifyHeartbeat(joinGroupResult, Errors.UNKNOWN_MEMBER_ID)
- }
- }
-
- @Test
- def testRebalanceTimesOutWhenSyncRequestIsNotReceivedFromLeaders(): Unit = {
- // This test case ensure that the DelayedSync does kick out the leader
- // if it does not sent a sync request before the rebalance timeout. The
- // group is in the CompletingRebalance state in this case.
- val results = joinWithNMembers(nbMembers = 3)
- assertEquals(Set(Errors.NONE), results.map(_.error).toSet)
-
- // Advance time
- timer.advanceClock(DefaultRebalanceTimeout / 2)
-
- // Heartbeats to ensure that heartbeating does not interfere with the
- // delayed sync operation.
- results.foreach { joinGroupResult =>
- verifyHeartbeat(joinGroupResult, Errors.NONE)
- }
-
- // Followers send Sync
- val followerResults = results.tail.map { joinGroupResult =>
- sendSyncGroupFollower(groupId, joinGroupResult.generationId, joinGroupResult.memberId,
- Some(protocolType), Some(protocolName), None)
- }
-
- // Advance part the rebalance timeout to trigger the delayed operation.
- timer.advanceClock(DefaultRebalanceTimeout / 2 + 1)
-
- val followerErrors = followerResults.map(await(_, 1).error)
- assertEquals(Set(Errors.REBALANCE_IN_PROGRESS), followerErrors.toSet)
-
- // Leader should have been removed.
- verifyHeartbeat(results.head, Errors.UNKNOWN_MEMBER_ID)
-
- // Followers should be able to heartbeat.
- results.tail.foreach { joinGroupResult =>
- verifyHeartbeat(joinGroupResult, Errors.REBALANCE_IN_PROGRESS)
- }
- }
-
- @Test
- def testRebalanceDoesNotTimeOutWhenAllSyncAreReceived(): Unit = {
- // This test case ensure that the DelayedSync does not kick any
- // members out when they have all sent their sync requests.
- val results = joinWithNMembers(nbMembers = 3)
- assertEquals(Set(Errors.NONE), results.map(_.error).toSet)
-
- // Advance time
- timer.advanceClock(DefaultRebalanceTimeout / 2)
-
- // Heartbeats to ensure that heartbeating does not interfere with the
- // delayed sync operation.
- results.foreach { joinGroupResult =>
- verifyHeartbeat(joinGroupResult, Errors.NONE)
- }
-
- val assignments = results.map(result => result.memberId -> Array.empty[Byte]).toMap
- val leaderResult = sendSyncGroupLeader(groupId, results.head.generationId, results.head.memberId,
- Some(protocolType), Some(protocolName), None, assignments)
-
- assertEquals(Errors.NONE, await(leaderResult, 1).error)
-
- // Followers send Sync
- val followerResults = results.tail.map { joinGroupResult =>
- sendSyncGroupFollower(groupId, joinGroupResult.generationId, joinGroupResult.memberId,
- Some(protocolType), Some(protocolName), None)
- }
-
- val followerErrors = followerResults.map(await(_, 1).error)
- assertEquals(Set(Errors.NONE), followerErrors.toSet)
-
- // Advance past the rebalance timeout to expire the Sync timeout. All
- // members should remain and the group should not rebalance.
- timer.advanceClock(DefaultRebalanceTimeout / 2 + 1)
-
- // Followers should be able to heartbeat.
- results.foreach { joinGroupResult =>
- verifyHeartbeat(joinGroupResult, Errors.NONE)
- }
-
- // Advance a bit more.
- timer.advanceClock(DefaultRebalanceTimeout / 2)
-
- // Followers should be able to heartbeat.
- results.foreach { joinGroupResult =>
- verifyHeartbeat(joinGroupResult, Errors.NONE)
- }
- }
-
- private def group(groupId: String = groupId) = {
- groupCoordinator.groupManager.getGroup(groupId) match {
- case Some(g) => g
- case None => null
- }
- }
-
- private def assertGroupState(groupId: String = groupId,
- groupState: GroupState): Unit = {
- groupCoordinator.groupManager.getGroup(groupId) match {
- case Some(group) => assertEquals(groupState, group.currentState)
- case None => fail(s"Group $groupId not found in coordinator")
- }
- }
-
- private def joinGroupPartial(groupId: String,
- memberId: String,
- protocolType: String,
- protocols: List[(String, Array[Byte])],
- sessionTimeout: Int = DefaultSessionTimeout,
- rebalanceTimeout: Int = DefaultRebalanceTimeout): JoinGroupResult = {
- val requireKnownMemberId = true
- val responseFuture = sendJoinGroup(groupId, memberId, protocolType, protocols, None, sessionTimeout, rebalanceTimeout, requireKnownMemberId)
- Await.result(responseFuture, Duration(rebalanceTimeout + 100, TimeUnit.MILLISECONDS))
- }
-
- @Test
- def testLeaderFailureInSyncGroup(): Unit = {
- // to get a group of two members:
- // 1. join and sync with a single member (because we can't immediately join with two members)
- // 2. join and sync with the first member and a new member
-
- val firstJoinResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val firstMemberId = firstJoinResult.memberId
- val firstGenerationId = firstJoinResult.generationId
- assertEquals(firstMemberId, firstJoinResult.leaderId)
- assertEquals(Errors.NONE, firstJoinResult.error)
-
- val firstSyncResult = syncGroupLeader(groupId, firstGenerationId, firstMemberId, Map(firstMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, firstSyncResult.error)
-
- val otherJoinFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
-
- val joinFuture = sendJoinGroup(groupId, firstMemberId, protocolType, protocols)
-
- val joinResult = await(joinFuture, DefaultSessionTimeout+100)
- val otherJoinResult = await(otherJoinFuture, DefaultSessionTimeout+100)
- assertEquals(Errors.NONE, joinResult.error)
- assertEquals(Errors.NONE, otherJoinResult.error)
- assertTrue(joinResult.generationId == otherJoinResult.generationId)
-
- assertEquals(firstMemberId, joinResult.leaderId)
- assertEquals(firstMemberId, otherJoinResult.leaderId)
-
- val nextGenerationId = joinResult.generationId
-
- // with no leader SyncGroup, the follower's request should fail with an error indicating
- // that it should rejoin
- val followerSyncFuture = sendSyncGroupFollower(groupId, nextGenerationId, otherJoinResult.memberId, None, None, None)
-
- timer.advanceClock(DefaultSessionTimeout + 100)
-
- val followerSyncResult = await(followerSyncFuture, DefaultSessionTimeout+100)
- assertEquals(Errors.REBALANCE_IN_PROGRESS, followerSyncResult.error)
- }
-
- @Test
- def testSyncGroupFollowerAfterLeader(): Unit = {
- // to get a group of two members:
- // 1. join and sync with a single member (because we can't immediately join with two members)
- // 2. join and sync with the first member and a new member
-
- val firstJoinResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val firstMemberId = firstJoinResult.memberId
- val firstGenerationId = firstJoinResult.generationId
- assertEquals(firstMemberId, firstJoinResult.leaderId)
- assertEquals(Errors.NONE, firstJoinResult.error)
-
- val firstSyncResult = syncGroupLeader(groupId, firstGenerationId, firstMemberId, Map(firstMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, firstSyncResult.error)
-
- val otherJoinFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
-
- val joinFuture = sendJoinGroup(groupId, firstMemberId, protocolType, protocols)
-
- val joinResult = await(joinFuture, DefaultSessionTimeout+100)
- val otherJoinResult = await(otherJoinFuture, DefaultSessionTimeout+100)
- assertEquals(Errors.NONE, joinResult.error)
- assertEquals(Errors.NONE, otherJoinResult.error)
- assertTrue(joinResult.generationId == otherJoinResult.generationId)
-
- assertEquals(firstMemberId, joinResult.leaderId)
- assertEquals(firstMemberId, otherJoinResult.leaderId)
-
- val nextGenerationId = joinResult.generationId
- val leaderId = firstMemberId
- val leaderAssignment = Array[Byte](0)
- val followerId = otherJoinResult.memberId
- val followerAssignment = Array[Byte](1)
-
- val leaderSyncResult = syncGroupLeader(groupId, nextGenerationId, leaderId,
- Map(leaderId -> leaderAssignment, followerId -> followerAssignment))
- assertEquals(Errors.NONE, leaderSyncResult.error)
- assertEquals(leaderAssignment, leaderSyncResult.memberAssignment)
-
- val followerSyncResult = syncGroupFollower(groupId, nextGenerationId, otherJoinResult.memberId)
- assertEquals(Errors.NONE, followerSyncResult.error)
- assertEquals(followerAssignment, followerSyncResult.memberAssignment)
- }
-
- @Test
- def testSyncGroupLeaderAfterFollower(): Unit = {
- // to get a group of two members:
- // 1. join and sync with a single member (because we can't immediately join with two members)
- // 2. join and sync with the first member and a new member
-
- val joinGroupResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val firstMemberId = joinGroupResult.memberId
- val firstGenerationId = joinGroupResult.generationId
- assertEquals(firstMemberId, joinGroupResult.leaderId)
- assertEquals(Errors.NONE, joinGroupResult.error)
-
- val syncGroupResult = syncGroupLeader(groupId, firstGenerationId, firstMemberId, Map(firstMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- val otherJoinFuture = sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
-
- val joinFuture = sendJoinGroup(groupId, firstMemberId, protocolType, protocols)
-
- val joinResult = await(joinFuture, DefaultSessionTimeout+100)
- val otherJoinResult = await(otherJoinFuture, DefaultSessionTimeout+100)
- assertEquals(Errors.NONE, joinResult.error)
- assertEquals(Errors.NONE, otherJoinResult.error)
- assertTrue(joinResult.generationId == otherJoinResult.generationId)
-
- val nextGenerationId = joinResult.generationId
- val leaderId = joinResult.leaderId
- val leaderAssignment = Array[Byte](0)
- val followerId = otherJoinResult.memberId
- val followerAssignment = Array[Byte](1)
-
- assertEquals(firstMemberId, joinResult.leaderId)
- assertEquals(firstMemberId, otherJoinResult.leaderId)
-
- val followerSyncFuture = sendSyncGroupFollower(groupId, nextGenerationId, followerId, None, None, None)
-
- val leaderSyncResult = syncGroupLeader(groupId, nextGenerationId, leaderId,
- Map(leaderId -> leaderAssignment, followerId -> followerAssignment))
- assertEquals(Errors.NONE, leaderSyncResult.error)
- assertEquals(leaderAssignment, leaderSyncResult.memberAssignment)
-
- val followerSyncResult = await(followerSyncFuture, DefaultSessionTimeout+100)
- assertEquals(Errors.NONE, followerSyncResult.error)
- assertEquals(followerAssignment, followerSyncResult.memberAssignment)
- }
-
- @Test
- def testCommitOffsetFromUnknownGroup(): Unit = {
- val generationId = 1
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
-
- val commitOffsetResult = commitOffsets(groupId, memberId, generationId, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.ILLEGAL_GENERATION), commitOffsetResult)
- }
-
- @Test
- def testCommitOffsetWithDefaultGeneration(): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
-
- val commitOffsetResult = commitOffsets(groupId, OffsetCommitRequest.DEFAULT_MEMBER_ID,
- OffsetCommitRequest.DEFAULT_GENERATION_ID, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.NONE), commitOffsetResult)
- }
-
- @Test
- def testCommitOffsetsAfterGroupIsEmpty(): Unit = {
- // Tests the scenario where the reset offset tool modifies the offsets
- // of a group after it becomes empty
-
- // A group member joins
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedMemberId = joinGroupResult.memberId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- // and leaves.
- val leaveGroupResults = singleLeaveGroup(groupId, assignedMemberId)
- verifyLeaveGroupResult(leaveGroupResults)
-
- // The simple offset commit should now fail
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
- val commitOffsetResult = commitOffsets(groupId, OffsetCommitRequest.DEFAULT_MEMBER_ID,
- OffsetCommitRequest.DEFAULT_GENERATION_ID, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.NONE), commitOffsetResult)
-
- val (error, partitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
- assertEquals(Errors.NONE, error)
- assertEquals(Some(0), partitionData.get(tip.topicPartition).map(_.offset))
- }
-
- @Test
- def testFetchOffsets(): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = 97L
- val metadata = "some metadata"
- val leaderEpoch = OptionalInt.of(15)
- val offsetAndMetadata = new OffsetAndMetadata(offset, leaderEpoch, metadata, timer.time.milliseconds(), OptionalLong.empty)
-
- val commitOffsetResult = commitOffsets(groupId, OffsetCommitRequest.DEFAULT_MEMBER_ID,
- OffsetCommitRequest.DEFAULT_GENERATION_ID, Map(tip -> offsetAndMetadata))
- assertEquals(Map(tip -> Errors.NONE), commitOffsetResult)
-
- val (error, partitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
- assertEquals(Errors.NONE, error)
-
- val maybePartitionData = partitionData.get(tip.topicPartition)
- assertTrue(maybePartitionData.isDefined)
- assertEquals(offset, maybePartitionData.get.offset)
- assertEquals(metadata, maybePartitionData.get.metadata)
- assertEquals(leaderEpoch.getAsInt, maybePartitionData.get.leaderEpoch.get)
- }
-
- @Test
- def testCommitAndFetchOffsetsWithEmptyGroup(): Unit = {
- // For backwards compatibility, the coordinator supports committing/fetching offsets with an empty groupId.
- // To allow inspection and removal of the empty group, we must also support DescribeGroups and DeleteGroups
-
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
- val groupId = ""
-
- val commitOffsetResult = commitOffsets(groupId, OffsetCommitRequest.DEFAULT_MEMBER_ID,
- OffsetCommitRequest.DEFAULT_GENERATION_ID, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.NONE), commitOffsetResult)
-
- val (fetchError, partitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
- assertEquals(Errors.NONE, fetchError)
- assertEquals(Some(0), partitionData.get(tip.topicPartition).map(_.offset))
-
- var (describeError, describeErrorMessage, summary) = groupCoordinator.handleDescribeGroup(groupId, ApiKeys.DESCRIBE_GROUPS.latestVersion)
- assertEquals(Errors.NONE, describeError)
- assertTrue(describeErrorMessage.isEmpty)
- assertEquals(Empty.toString, summary.state)
-
- val groupTopicPartition = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, groupPartitionId)
- val partition: Partition = mock(classOf[Partition])
-
- when(replicaManager.getPartition(groupTopicPartition)).thenReturn(HostedPartition.Online(partition))
- when(replicaManager.onlinePartition(groupTopicPartition)).thenReturn(Some(partition))
-
- val deleteErrors = groupCoordinator.handleDeleteGroups(Set(groupId))
- assertEquals(Errors.NONE, deleteErrors(groupId))
-
- val (err, data) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
- assertEquals(Errors.NONE, err)
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), data.get(tip.topicPartition).map(_.offset))
- }
-
- @Test
- def testBasicFetchTxnOffsets(): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
- val producerId = 1000L
- val producerEpoch : Short = 2
-
- val commitOffsetResult = commitTransactionalOffsets(groupId, producerId, producerEpoch, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.NONE), commitOffsetResult)
-
- val (error, partitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
-
- // Validate that the offset isn't materialized yet.
- assertEquals(Errors.NONE, error)
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), partitionData.get(tip.topicPartition).map(_.offset))
-
- val offsetsTopic = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, groupPartitionId)
-
- // Send commit marker.
- handleTxnCompletion(producerId, List(offsetsTopic), TransactionResult.COMMIT)
-
- // Validate that committed offset is materialized.
- val (secondReqError, secondReqPartitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
- assertEquals(Errors.NONE, secondReqError)
- assertEquals(Some(0), secondReqPartitionData.get(tip.topicPartition).map(_.offset))
- }
-
- @Test
- def testFetchTxnOffsetsWithAbort(): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
- val producerId = 1000L
- val producerEpoch : Short = 2
-
- val commitOffsetResult = commitTransactionalOffsets(groupId, producerId, producerEpoch, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.NONE), commitOffsetResult)
-
- val (error, partitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
- assertEquals(Errors.NONE, error)
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), partitionData.get(tip.topicPartition).map(_.offset))
-
- val offsetsTopic = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, groupPartitionId)
-
- // Validate that the pending commit is discarded.
- handleTxnCompletion(producerId, List(offsetsTopic), TransactionResult.ABORT)
-
- val (secondReqError, secondReqPartitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
- assertEquals(Errors.NONE, secondReqError)
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), secondReqPartitionData.get(tip.topicPartition).map(_.offset))
- }
-
- @Test
- def testFetchPendingTxnOffsetsWithAbort(): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
- val producerId = 1000L
- val producerEpoch : Short = 2
-
- val commitOffsetResult = commitTransactionalOffsets(groupId, producerId, producerEpoch, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.NONE), commitOffsetResult)
-
- val nonExistTp = new TopicPartition("non-exist-topic", 0)
- val (error, partitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition, nonExistTp)))
- assertEquals(Errors.NONE, error)
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), partitionData.get(tip.topicPartition).map(_.offset))
- assertEquals(Some(Errors.UNSTABLE_OFFSET_COMMIT), partitionData.get(tip.topicPartition).map(_.error))
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), partitionData.get(nonExistTp).map(_.offset))
- assertEquals(Some(Errors.NONE), partitionData.get(nonExistTp).map(_.error))
-
- val offsetsTopic = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, groupPartitionId)
-
- // Validate that the pending commit is discarded.
- handleTxnCompletion(producerId, List(offsetsTopic), TransactionResult.ABORT)
-
- val (secondReqError, secondReqPartitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
- assertEquals(Errors.NONE, secondReqError)
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), secondReqPartitionData.get(tip.topicPartition).map(_.offset))
- assertEquals(Some(Errors.NONE), secondReqPartitionData.get(tip.topicPartition).map(_.error))
- }
-
- @Test
- def testFetchPendingTxnOffsetsWithCommit(): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "offset")
- val offset = offsetAndMetadata(25)
- val producerId = 1000L
- val producerEpoch : Short = 2
-
- val commitOffsetResult = commitTransactionalOffsets(groupId, producerId, producerEpoch, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.NONE), commitOffsetResult)
-
- val (error, partitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
- assertEquals(Errors.NONE, error)
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), partitionData.get(tip.topicPartition).map(_.offset))
- assertEquals(Some(Errors.UNSTABLE_OFFSET_COMMIT), partitionData.get(tip.topicPartition).map(_.error))
-
- val offsetsTopic = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, groupPartitionId)
-
- // Validate that the pending commit is committed
- handleTxnCompletion(producerId, List(offsetsTopic), TransactionResult.COMMIT)
-
- val (secondReqError, secondReqPartitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
- assertEquals(Errors.NONE, secondReqError)
- assertEquals(Some(25), secondReqPartitionData.get(tip.topicPartition).map(_.offset))
- assertEquals(Some(Errors.NONE), secondReqPartitionData.get(tip.topicPartition).map(_.error))
- }
-
- @Test
- def testFetchTxnOffsetsIgnoreSpuriousCommit(): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
- val producerId = 1000L
- val producerEpoch : Short = 2
-
- val commitOffsetResult = commitTransactionalOffsets(groupId, producerId, producerEpoch, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.NONE), commitOffsetResult)
-
- val (error, partitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
- assertEquals(Errors.NONE, error)
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), partitionData.get(tip.topicPartition).map(_.offset))
-
- val offsetsTopic = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, groupPartitionId)
- handleTxnCompletion(producerId, List(offsetsTopic), TransactionResult.ABORT)
-
- val (secondReqError, secondReqPartitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
- assertEquals(Errors.NONE, secondReqError)
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), secondReqPartitionData.get(tip.topicPartition).map(_.offset))
-
- // Ignore spurious commit.
- handleTxnCompletion(producerId, List(offsetsTopic), TransactionResult.COMMIT)
-
- val (thirdReqError, thirdReqPartitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tip.topicPartition)))
- assertEquals(Errors.NONE, thirdReqError)
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), thirdReqPartitionData.get(tip.topicPartition).map(_.offset))
- }
-
- @Test
- def testFetchTxnOffsetsOneProducerMultipleGroups(): Unit = {
- // One producer, two groups located on separate offsets topic partitions.
- // Both group have pending offset commits.
- // Marker for only one partition is received. That commit should be materialized while the other should not.
-
- val topicIdPartitions = List(
- new TopicIdPartition(Uuid.randomUuid(), 0, "topic1"),
- new TopicIdPartition(Uuid.randomUuid(), 0, "topic2")
- )
- val offsets = List(offsetAndMetadata(10), offsetAndMetadata(15))
- val producerId = 1000L
- val producerEpoch: Short = 3
-
- val groupIds = List(groupId, otherGroupId)
- val offsetTopicPartitions = List(new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, groupCoordinator.partitionFor(groupId)),
- new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, groupCoordinator.partitionFor(otherGroupId)))
-
- groupCoordinator.groupManager.addOwnedPartition(offsetTopicPartitions(1).partition)
- val errors = mutable.ArrayBuffer[Errors]()
- val partitionData = mutable.ArrayBuffer[scala.collection.Map[TopicPartition, OffsetFetchResponse.PartitionData]]()
-
- val commitOffsetResults = mutable.ArrayBuffer[CommitOffsetCallbackParams]()
-
- // Ensure that the two groups map to different partitions.
- assertNotEquals(offsetTopicPartitions(0), offsetTopicPartitions(1))
-
- commitOffsetResults.append(commitTransactionalOffsets(groupId, producerId, producerEpoch, Map(topicIdPartitions(0) -> offsets(0))))
- assertEquals(Errors.NONE, commitOffsetResults(0)(topicIdPartitions(0)))
- commitOffsetResults.append(commitTransactionalOffsets(otherGroupId, producerId, producerEpoch, Map(topicIdPartitions(1) -> offsets(1))))
- assertEquals(Errors.NONE, commitOffsetResults(1)(topicIdPartitions(1)))
-
- // We got a commit for only one __consumer_offsets partition. We should only materialize it's group offsets.
- val topicPartitions = topicIdPartitions.map(_.topicPartition)
- handleTxnCompletion(producerId, List(offsetTopicPartitions(0)), TransactionResult.COMMIT)
- groupCoordinator.handleFetchOffsets(groupIds(0), requireStable, Some(topicPartitions)) match {
- case (error, partData) =>
- errors.append(error)
- partitionData.append(partData)
- case _ =>
- }
-
- groupCoordinator.handleFetchOffsets(groupIds(1), requireStable, Some(topicPartitions)) match {
- case (error, partData) =>
- errors.append(error)
- partitionData.append(partData)
- case _ =>
- }
-
- assertEquals(2, errors.size)
- assertEquals(Errors.NONE, errors(0))
- assertEquals(Errors.NONE, errors(1))
-
- // Exactly one offset commit should have been materialized.
- assertEquals(Some(offsets(0).committedOffset), partitionData(0).get(topicPartitions(0)).map(_.offset))
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), partitionData(0).get(topicPartitions(1)).map(_.offset))
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), partitionData(1).get(topicPartitions(0)).map(_.offset))
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), partitionData(1).get(topicPartitions(1)).map(_.offset))
-
- // Now we receive the other marker.
- handleTxnCompletion(producerId, List(offsetTopicPartitions(1)), TransactionResult.COMMIT)
- errors.clear()
- partitionData.clear()
- groupCoordinator.handleFetchOffsets(groupIds(0), requireStable, Some(topicPartitions)) match {
- case (error, partData) =>
- errors.append(error)
- partitionData.append(partData)
- case _ =>
- }
-
- groupCoordinator.handleFetchOffsets(groupIds(1), requireStable, Some(topicPartitions)) match {
- case (error, partData) =>
- errors.append(error)
- partitionData.append(partData)
- case _ =>
- }
- // Two offsets should have been materialized
- assertEquals(Some(offsets(0).committedOffset), partitionData(0).get(topicPartitions(0)).map(_.offset))
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), partitionData(0).get(topicPartitions(1)).map(_.offset))
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), partitionData(1).get(topicPartitions(0)).map(_.offset))
- assertEquals(Some(offsets(1).committedOffset), partitionData(1).get(topicPartitions(1)).map(_.offset))
- }
-
- @Test
- def testFetchTxnOffsetsMultipleProducersOneGroup(): Unit = {
- // One group, two producers
- // Different producers will commit offsets for different partitions.
- // Each partition's offsets should be materialized when the corresponding producer's marker is received.
-
- val topicIdPartitions = List(
- new TopicIdPartition(Uuid.randomUuid(), 0, "topic1"),
- new TopicIdPartition(Uuid.randomUuid(), 0, "topic2")
- )
- val offsets = List(offsetAndMetadata(10), offsetAndMetadata(15))
- val producerIds = List(1000L, 1005L)
- val producerEpochs: Seq[Short] = List(3, 4)
-
- val offsetTopicPartition = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, groupCoordinator.partitionFor(groupId))
-
- val errors = mutable.ArrayBuffer[Errors]()
- val partitionData = mutable.ArrayBuffer[scala.collection.Map[TopicPartition, OffsetFetchResponse.PartitionData]]()
-
- val commitOffsetResults = mutable.ArrayBuffer[CommitOffsetCallbackParams]()
-
- // producer0 commits the offsets for partition0
- commitOffsetResults.append(commitTransactionalOffsets(groupId, producerIds(0), producerEpochs(0), Map(topicIdPartitions(0) -> offsets(0))))
- assertEquals(Errors.NONE, commitOffsetResults(0)(topicIdPartitions(0)))
-
- // producer1 commits the offsets for partition1
- commitOffsetResults.append(commitTransactionalOffsets(groupId, producerIds(1), producerEpochs(1), Map(topicIdPartitions(1) -> offsets(1))))
- assertEquals(Errors.NONE, commitOffsetResults(1)(topicIdPartitions(1)))
-
- // producer0 commits its transaction.
- val topicPartitions = topicIdPartitions.map(_.topicPartition)
- handleTxnCompletion(producerIds(0), List(offsetTopicPartition), TransactionResult.COMMIT)
- groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(topicPartitions)) match {
- case (error, partData) =>
- errors.append(error)
- partitionData.append(partData)
- case _ =>
- }
-
- assertEquals(Errors.NONE, errors(0))
-
- // We should only see the offset commit for producer0
- assertEquals(Some(offsets(0).committedOffset), partitionData(0).get(topicPartitions(0)).map(_.offset))
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), partitionData(0).get(topicPartitions(1)).map(_.offset))
-
- // producer1 now commits its transaction.
- handleTxnCompletion(producerIds(1), List(offsetTopicPartition), TransactionResult.COMMIT)
-
- groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(topicPartitions)) match {
- case (error, partData) =>
- errors.append(error)
- partitionData.append(partData)
- case _ =>
- }
-
- assertEquals(Errors.NONE, errors(1))
-
- // We should now see the offset commits for both producers.
- assertEquals(Some(offsets(0).committedOffset), partitionData(1).get(topicPartitions(0)).map(_.offset))
- assertEquals(Some(offsets(1).committedOffset), partitionData(1).get(topicPartitions(1)).map(_.offset))
- }
-
- @Test
- def testFetchOffsetForUnknownPartition(): Unit = {
- val tp = new TopicPartition("topic", 0)
- val (error, partitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable, Some(Seq(tp)))
- assertEquals(Errors.NONE, error)
- assertEquals(Some(OffsetFetchResponse.INVALID_OFFSET), partitionData.get(tp).map(_.offset))
- }
-
- @Test
- def testFetchOffsetNotCoordinatorForGroup(): Unit = {
- val tp = new TopicPartition("topic", 0)
- val (error, partitionData) = groupCoordinator.handleFetchOffsets(otherGroupId, requireStable, Some(Seq(tp)))
- assertEquals(Errors.NOT_COORDINATOR, error)
- assertTrue(partitionData.isEmpty)
- }
-
- @Test
- def testFetchAllOffsets(): Unit = {
- val tip1 = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val tip2 = new TopicIdPartition(tip1.topicId, 1, "topic")
- val tip3 = new TopicIdPartition(Uuid.randomUuid(), 0, "other-topic")
- val offset1 = offsetAndMetadata(15)
- val offset2 = offsetAndMetadata(16)
- val offset3 = offsetAndMetadata(17)
-
- assertEquals((Errors.NONE, Map.empty), groupCoordinator.handleFetchOffsets(groupId, requireStable))
-
- val commitOffsetResult = commitOffsets(groupId, OffsetCommitRequest.DEFAULT_MEMBER_ID,
- OffsetCommitRequest.DEFAULT_GENERATION_ID, Map(tip1 -> offset1, tip2 -> offset2, tip3 -> offset3))
- assertEquals(Map(tip1 -> Errors.NONE, tip2 -> Errors.NONE, tip3 -> Errors.NONE), commitOffsetResult)
-
- val (error, partitionData) = groupCoordinator.handleFetchOffsets(groupId, requireStable)
- assertEquals(Errors.NONE, error)
- assertEquals(3, partitionData.size)
- assertTrue(partitionData.forall(_._2.error == Errors.NONE))
- assertEquals(Some(offset1.committedOffset), partitionData.get(tip1.topicPartition).map(_.offset))
- assertEquals(Some(offset2.committedOffset), partitionData.get(tip2.topicPartition).map(_.offset))
- assertEquals(Some(offset3.committedOffset), partitionData.get(tip3.topicPartition).map(_.offset))
- }
-
- @Test
- def testCommitOffsetInCompletingRebalance(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedMemberId = joinGroupResult.memberId
- val generationId = joinGroupResult.generationId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val commitOffsetResult = commitOffsets(groupId, assignedMemberId, generationId, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.REBALANCE_IN_PROGRESS), commitOffsetResult)
- }
-
- @Test
- def testCommitOffsetInCompletingRebalanceFromUnknownMemberId(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0 , "topic")
- val offset = offsetAndMetadata(0)
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val generationId = joinGroupResult.generationId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val commitOffsetResult = commitOffsets(groupId, memberId, generationId, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.UNKNOWN_MEMBER_ID), commitOffsetResult)
- }
-
- @Test
- def testCommitOffsetInCompletingRebalanceFromIllegalGeneration(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedMemberId = joinGroupResult.memberId
- val generationId = joinGroupResult.generationId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val commitOffsetResult = commitOffsets(groupId, assignedMemberId, generationId + 1, Map(tip -> offset))
- assertEquals(Map(tip -> Errors.ILLEGAL_GENERATION), commitOffsetResult)
- }
-
- @Test
- def testManualCommitOffsetShouldNotValidateMemberIdAndInstanceId(): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
-
- var commitOffsetResult = commitOffsets(
- groupId,
- JoinGroupRequest.UNKNOWN_MEMBER_ID,
- -1,
- Map(tip -> offsetAndMetadata(0)),
- Some("instance-id")
- )
- assertEquals(Map(tip -> Errors.NONE), commitOffsetResult)
-
- commitOffsetResult = commitOffsets(
- groupId,
- "unknown",
- -1,
- Map(tip -> offsetAndMetadata(0)),
- None
- )
- assertEquals(Map(tip -> Errors.NONE), commitOffsetResult)
- }
-
- @Test
- def testTxnCommitOffsetWithFencedInstanceId(): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
- val producerId = 1000L
- val producerEpoch : Short = 2
-
- val rebalanceResult = staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- val leaderNoMemberIdCommitOffsetResult = commitTransactionalOffsets(groupId, producerId, producerEpoch,
- Map(tip -> offset), memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID, groupInstanceId = Some(leaderInstanceId))
- assertEquals(Map(tip -> Errors.FENCED_INSTANCE_ID), leaderNoMemberIdCommitOffsetResult)
-
- val leaderInvalidMemberIdCommitOffsetResult = commitTransactionalOffsets(groupId, producerId, producerEpoch,
- Map(tip -> offset), memberId = "invalid-member", groupInstanceId = Some(leaderInstanceId))
- assertEquals(Map(tip -> Errors.FENCED_INSTANCE_ID), leaderInvalidMemberIdCommitOffsetResult)
-
- val leaderCommitOffsetResult = commitTransactionalOffsets(groupId, producerId, producerEpoch,
- Map(tip -> offset), rebalanceResult.leaderId, Some(leaderInstanceId), rebalanceResult.generation)
- assertEquals(Map(tip -> Errors.NONE), leaderCommitOffsetResult)
- }
-
- @Test
- def testTxnCommitOffsetWithInvalidMemberId(): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
- val producerId = 1000L
- val producerEpoch : Short = 2
-
- val joinGroupResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val invalidIdCommitOffsetResult = commitTransactionalOffsets(groupId, producerId, producerEpoch,
- Map(tip -> offset), "invalid-member")
- assertEquals(Map(tip -> Errors.UNKNOWN_MEMBER_ID), invalidIdCommitOffsetResult)
- }
-
- @Test
- def testTxnCommitOffsetWithKnownMemberId(): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
- val producerId = 1000L
- val producerEpoch : Short = 2
-
- val joinGroupResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
-
- val assignedConsumerId = joinGroupResult.memberId
- val leaderCommitOffsetResult = commitTransactionalOffsets(groupId, producerId, producerEpoch,
- Map(tip -> offset), assignedConsumerId, generationId = joinGroupResult.generationId)
- assertEquals(Map(tip -> Errors.NONE), leaderCommitOffsetResult)
- }
-
- @Test
- def testTxnCommitOffsetWithIllegalGeneration(): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
- val producerId = 1000L
- val producerEpoch : Short = 2
-
- val joinGroupResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
-
- val assignedConsumerId = joinGroupResult.memberId
- val initialGenerationId = joinGroupResult.generationId
- val illegalGenerationCommitOffsetResult = commitTransactionalOffsets(groupId, producerId, producerEpoch,
- Map(tip -> offset), memberId = assignedConsumerId, generationId = initialGenerationId + 5)
- assertEquals(Map(tip -> Errors.ILLEGAL_GENERATION), illegalGenerationCommitOffsetResult)
- }
-
- @Test
- def testTxnCommitOffsetWithLegalGeneration(): Unit = {
- val tip = new TopicIdPartition(Uuid.randomUuid(), 0, "topic")
- val offset = offsetAndMetadata(0)
- val producerId = 1000L
- val producerEpoch : Short = 2
-
- val joinGroupResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
-
- val assignedConsumerId = joinGroupResult.memberId
- val initialGenerationId = joinGroupResult.generationId
- val leaderCommitOffsetResult = commitTransactionalOffsets(groupId, producerId, producerEpoch,
- Map(tip -> offset), memberId = assignedConsumerId, generationId = initialGenerationId)
- assertEquals(Map(tip -> Errors.NONE), leaderCommitOffsetResult)
- }
-
- @Test
- def testHeartbeatDuringRebalanceCausesRebalanceInProgress(): Unit = {
- // First start up a group (with a slightly larger timeout to give us time to heartbeat when the rebalance starts)
- val joinGroupResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val assignedConsumerId = joinGroupResult.memberId
- val initialGenerationId = joinGroupResult.generationId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- // Then join with a new consumer to trigger a rebalance
- sendJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
-
- // We should be in the middle of a rebalance, so the heartbeat should return rebalance in progress
- val heartbeatResult = heartbeat(groupId, assignedConsumerId, initialGenerationId)
- assertEquals(Errors.REBALANCE_IN_PROGRESS, heartbeatResult)
- }
-
- @Test
- def testGenerationIdIncrementsOnRebalance(): Unit = {
- val joinGroupResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val initialGenerationId = joinGroupResult.generationId
- val joinGroupError = joinGroupResult.error
- val memberId = joinGroupResult.memberId
- assertEquals(1, initialGenerationId)
- assertEquals(Errors.NONE, joinGroupError)
-
- val syncGroupResult = syncGroupLeader(groupId, initialGenerationId, memberId, Map(memberId -> Array[Byte]()))
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- val joinGroupFuture = sendJoinGroup(groupId, memberId, protocolType, protocols)
- val otherJoinGroupResult = await(joinGroupFuture, 1)
-
- val nextGenerationId = otherJoinGroupResult.generationId
- val otherJoinGroupError = otherJoinGroupResult.error
- assertEquals(2, nextGenerationId)
- assertEquals(Errors.NONE, otherJoinGroupError)
- }
-
- @Test
- def testLeaveGroupWrongCoordinator(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val leaveGroupResults = singleLeaveGroup(otherGroupId, memberId)
- verifyLeaveGroupResult(leaveGroupResults, Errors.NOT_COORDINATOR)
- }
-
- @Test
- def testLeaveGroupUnknownGroup(): Unit = {
- val leaveGroupResults = singleLeaveGroup(groupId, memberId)
- verifyLeaveGroupResult(leaveGroupResults, Errors.NONE, List(Errors.UNKNOWN_MEMBER_ID))
- }
-
- @Test
- def testLeaveGroupUnknownConsumerExistingGroup(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val otherMemberId = "consumerId"
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val leaveGroupResults = singleLeaveGroup(groupId, otherMemberId)
- verifyLeaveGroupResult(leaveGroupResults, Errors.NONE, List(Errors.UNKNOWN_MEMBER_ID))
- }
-
- @Test
- def testSingleLeaveDeadGroup(): Unit = {
- val deadGroupId = "deadGroupId"
-
- groupCoordinator.groupManager.addGroup(new GroupMetadata(deadGroupId, Dead, new MockTime()))
- val leaveGroupResults = singleLeaveGroup(deadGroupId, memberId)
- verifyLeaveGroupResult(leaveGroupResults, Errors.COORDINATOR_NOT_AVAILABLE)
- }
-
- @Test
- def testBatchLeaveDeadGroup(): Unit = {
- val deadGroupId = "deadGroupId"
-
- groupCoordinator.groupManager.addGroup(new GroupMetadata(deadGroupId, Dead, new MockTime()))
- val leaveGroupResults = batchLeaveGroup(deadGroupId,
- List(new MemberIdentity().setMemberId(memberId), new MemberIdentity().setMemberId(memberId)))
- verifyLeaveGroupResult(leaveGroupResults, Errors.COORDINATOR_NOT_AVAILABLE)
- }
-
- @Test
- def testValidLeaveGroup(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedMemberId = joinGroupResult.memberId
- val joinGroupError = joinGroupResult.error
- assertEquals(Errors.NONE, joinGroupError)
-
- val leaveGroupResults = singleLeaveGroup(groupId, assignedMemberId)
- verifyLeaveGroupResult(leaveGroupResults)
- }
-
- @Test
- def testLeaveGroupWithFencedInstanceId(): Unit = {
- val joinGroupResult = staticJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, leaderInstanceId, protocolType, protocolSuperset)
- assertEquals(Errors.NONE, joinGroupResult.error)
-
- val leaveGroupResults = singleLeaveGroup(groupId, "some_member", Some(leaderInstanceId))
- verifyLeaveGroupResult(leaveGroupResults, Errors.NONE, List(Errors.FENCED_INSTANCE_ID))
- }
-
- @Test
- def testLeaveGroupStaticMemberWithUnknownMemberId(): Unit = {
- val joinGroupResult = staticJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, leaderInstanceId, protocolType, protocolSuperset)
- assertEquals(Errors.NONE, joinGroupResult.error)
-
- // Having unknown member id will not affect the request processing.
- val leaveGroupResults = singleLeaveGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, Some(leaderInstanceId))
- verifyLeaveGroupResult(leaveGroupResults, Errors.NONE, List(Errors.NONE))
- }
-
- @Test
- def testStaticMembersValidBatchLeaveGroup(): Unit = {
- staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- val leaveGroupResults = batchLeaveGroup(groupId, List(new MemberIdentity()
- .setGroupInstanceId(leaderInstanceId), new MemberIdentity().setGroupInstanceId(followerInstanceId)))
-
- verifyLeaveGroupResult(leaveGroupResults, Errors.NONE, List(Errors.NONE, Errors.NONE))
- }
-
- @Test
- def testStaticMembersWrongCoordinatorBatchLeaveGroup(): Unit = {
- staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- val leaveGroupResults = batchLeaveGroup("invalid-group", List(new MemberIdentity()
- .setGroupInstanceId(leaderInstanceId), new MemberIdentity().setGroupInstanceId(followerInstanceId)))
-
- verifyLeaveGroupResult(leaveGroupResults, Errors.NOT_COORDINATOR)
- }
-
- @Test
- def testStaticMembersUnknownGroupBatchLeaveGroup(): Unit = {
- val leaveGroupResults = batchLeaveGroup(groupId, List(new MemberIdentity()
- .setGroupInstanceId(leaderInstanceId), new MemberIdentity().setGroupInstanceId(followerInstanceId)))
-
- verifyLeaveGroupResult(leaveGroupResults, Errors.NONE, List(Errors.UNKNOWN_MEMBER_ID, Errors.UNKNOWN_MEMBER_ID))
- }
-
- @Test
- def testStaticMembersFencedInstanceBatchLeaveGroup(): Unit = {
- staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- val leaveGroupResults = batchLeaveGroup(groupId, List(new MemberIdentity()
- .setGroupInstanceId(leaderInstanceId), new MemberIdentity()
- .setGroupInstanceId(followerInstanceId)
- .setMemberId("invalid-member")))
-
- verifyLeaveGroupResult(leaveGroupResults, Errors.NONE, List(Errors.NONE, Errors.FENCED_INSTANCE_ID))
- }
-
- @Test
- def testStaticMembersUnknownInstanceBatchLeaveGroup(): Unit = {
- staticMembersJoinAndRebalance(leaderInstanceId, followerInstanceId)
-
- val leaveGroupResults = batchLeaveGroup(groupId, List(new MemberIdentity()
- .setGroupInstanceId("unknown-instance"), new MemberIdentity()
- .setGroupInstanceId(followerInstanceId)))
-
- verifyLeaveGroupResult(leaveGroupResults, Errors.NONE, List(Errors.UNKNOWN_MEMBER_ID, Errors.NONE))
- }
-
- @Test
- def testPendingMemberBatchLeaveGroup(): Unit = {
- val pendingMember = setupGroupWithPendingMember()
-
- val leaveGroupResults = batchLeaveGroup(groupId, List(new MemberIdentity()
- .setGroupInstanceId("unknown-instance"), new MemberIdentity()
- .setMemberId(pendingMember.memberId)))
-
- verifyLeaveGroupResult(leaveGroupResults, Errors.NONE, List(Errors.UNKNOWN_MEMBER_ID, Errors.NONE))
- }
-
- @Test
- def testListGroupsIncludesStableGroups(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedMemberId = joinGroupResult.memberId
- val generationId = joinGroupResult.generationId
- assertEquals(Errors.NONE, joinGroupResult.error)
-
- val syncGroupResult = syncGroupLeader(groupId, generationId, assignedMemberId, Map(assignedMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- val (error, groups) = groupCoordinator.handleListGroups(Set(), Set())
- assertEquals(Errors.NONE, error)
- assertEquals(1, groups.size)
- assertEquals(GroupOverview("groupId", "consumer", Stable.toString, "classic"), groups.head)
- }
-
- @Test
- def testListGroupsIncludesRebalancingGroups(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- assertEquals(Errors.NONE, joinGroupResult.error)
-
- val (error, groups) = groupCoordinator.handleListGroups(Set(), Set())
- assertEquals(Errors.NONE, error)
- assertEquals(1, groups.size)
- assertEquals(GroupOverview("groupId", "consumer", CompletingRebalance.toString, "classic"), groups.head)
- }
-
- @Test
- def testListGroupsWithStates(): Unit = {
- val allStates = Set(PreparingRebalance, CompletingRebalance, Stable, Dead, Empty).map(s => s.toString)
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
-
- // Member joins the group
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedMemberId = joinGroupResult.memberId
- val generationId = joinGroupResult.generationId
- assertEquals(Errors.NONE, joinGroupResult.error)
-
- // The group should be in CompletingRebalance
- val (error, groups) = groupCoordinator.handleListGroups(Set(CompletingRebalance.toString), Set())
- assertEquals(Errors.NONE, error)
- assertEquals(1, groups.size)
- val (error2, groups2) = groupCoordinator.handleListGroups(allStates.filterNot(s => s == CompletingRebalance.toString), Set())
- assertEquals(Errors.NONE, error2)
- assertEquals(0, groups2.size)
-
- // Member syncs
- val syncGroupResult = syncGroupLeader(groupId, generationId, assignedMemberId, Map(assignedMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- // The group is now stable
- val (error3, groups3) = groupCoordinator.handleListGroups(Set(Stable.toString), Set())
- assertEquals(Errors.NONE, error3)
- assertEquals(1, groups3.size)
- val (error4, groups4) = groupCoordinator.handleListGroups(allStates.filterNot(s => s == Stable.toString), Set())
- assertEquals(Errors.NONE, error4)
- assertEquals(0, groups4.size)
-
- // Member leaves
- val leaveGroupResults = singleLeaveGroup(groupId, assignedMemberId)
- verifyLeaveGroupResult(leaveGroupResults)
-
- // The group is now empty
- val (error5, groups5) = groupCoordinator.handleListGroups(Set(Empty.toString), Set())
- assertEquals(Errors.NONE, error5)
- assertEquals(1, groups5.size)
- val (error6, groups6) = groupCoordinator.handleListGroups(allStates.filterNot(s => s == Empty.toString), Set())
- assertEquals(Errors.NONE, error6)
- assertEquals(0, groups6.size)
- }
-
- @Test
- def testListGroupsWithTypes(): Unit = {
- val memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID
- val joinGroupResult = dynamicJoinGroup(groupId, memberId, protocolType, protocols)
- val assignedMemberId = joinGroupResult.memberId
- val generationId = joinGroupResult.generationId
- assertEquals(Errors.NONE, joinGroupResult.error)
-
- val syncGroupResult = syncGroupLeader(groupId, generationId, assignedMemberId, Map(assignedMemberId -> Array[Byte]()))
- assertEquals(Errors.NONE, syncGroupResult.error)
-
- // When a group type filter is specified:
- // All groups are returned if the type is classic, else nothing is returned.
- val (error1, groups1) = groupCoordinator.handleListGroups(Set(), Set("classic"))
- assertEquals(Errors.NONE, error1)
- assertEquals(1, groups1.size)
- assertEquals(GroupOverview("groupId", "consumer", Stable.toString, "classic"), groups1.head)
-
- val (error2, groups2) = groupCoordinator.handleListGroups(Set(), Set("consumer"))
- assertEquals(Errors.NONE, error2)
- assertEquals(0, groups2.size)
-
- // No groups are returned when an incorrect group type is passed.
- val (error3, groups3) = groupCoordinator.handleListGroups(Set(), Set("Invalid"))
- assertEquals(Errors.NONE, error3)
- assertEquals(0, groups3.size)
-
- // When no group type filter is specified, all groups are returned with classic group type.
- val (error4, groups4) = groupCoordinator.handleListGroups(Set(), Set())
- assertEquals(Errors.NONE, error4)
- assertEquals(1, groups4.size)
- assertEquals(GroupOverview("groupId", "consumer", Stable.toString, "classic"), groups4.head)
-
- // Check that group type is case-insensitive.
- val (error5, groups5) = groupCoordinator.handleListGroups(Set(), Set("Classic"))
- assertEquals(Errors.NONE, error5)
- assertEquals(1, groups5.size)
- assertEquals(GroupOverview("groupId", "consumer", Stable.toString, "classic"), groups5.head)
- }
-
- @Test
- def testDescribeGroupWrongCoordinator(): Unit = {
- val (error, _, _) = groupCoordinator.handleDescribeGroup(otherGroupId, ApiKeys.DESCRIBE_GROUPS.latestVersion)
- assertEquals(Errors.NOT_COORDINATOR, error)
- }
-
- @Test
- def testDescribeGroupInactiveGroup(): Unit = {
- val (error, errorMessage, summary) = groupCoordinator.handleDescribeGroup(groupId, 5)
- assertEquals(Errors.NONE, error)
- assertTrue(errorMessage.isEmpty)
- assertEquals(GroupCoordinator.DeadGroup, summary)
-
- val (errorV6, errorMessageV6, summaryV6) = groupCoordinator.handleDescribeGroup(groupId, 6)
- assertEquals(Errors.GROUP_ID_NOT_FOUND, errorV6)
- assertEquals(s"Group $groupId not found.", errorMessageV6.get)
- assertEquals(GroupCoordinator.DeadGroup, summaryV6)
- }
-
- @Test
- def testDescribeGroupStableForDynamicMember(): Unit = {
- val joinGroupResult = dynamicJoinGroup(groupId, JoinGroupRequest.UNKNOWN_MEMBER_ID, protocolType, protocols)
- val assignedMemberId = joinGroupResult.memberId
- val generationId = joinGroupResult.generationId
... 4994 lines suppressed ...