You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by GitBox <gi...@apache.org> on 2021/03/22 11:23:38 UTC

[GitHub] [kafka] chia7712 commented on a change in pull request #10371: KAFKA-12479: Batch partition offset requests in ConsumerGroupCommand

chia7712 commented on a change in pull request #10371:
URL: https://github.com/apache/kafka/pull/10371#discussion_r598620622



##########
File path: core/src/test/scala/unit/kafka/admin/ConsumerGroupServiceTest.scala
##########
@@ -0,0 +1,133 @@
+/**
+ * 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.admin
+
+import java.util
+import java.util.{Collections, Optional}
+
+import kafka.admin.ConsumerGroupCommand.{ConsumerGroupCommandOptions, ConsumerGroupService}
+import org.apache.kafka.clients.admin._
+import org.apache.kafka.clients.consumer.{OffsetAndMetadata, RangeAssignor}
+import org.apache.kafka.common.{ConsumerGroupState, KafkaFuture, Node, TopicPartition, TopicPartitionInfo}
+import org.easymock.EasyMock
+import org.easymock.EasyMock._
+import org.junit.jupiter.api.Assertions.{assertEquals, assertTrue}
+import org.junit.jupiter.api.Test
+
+import scala.jdk.CollectionConverters._
+
+class ConsumerGroupServiceTest {
+
+  private val group = "testGroup"
+  private val topics = (0 until 5).map { i => s"testTopic$i" }
+  private val numPartitions = 10
+  private val topicPartitions = topics.flatMap { topic => (0 until numPartitions).map { i => new TopicPartition(topic, i) }}
+  private val admin: Admin = mock(classOf[Admin])
+
+  @Test
+  def testAdminRequestsForDescribeOffsets(): Unit = {
+    val args = Array("--bootstrap-server", "localhost:9092", "--group", group, "--describe", "--offsets")
+    val groupService = consumerGroupService(args)
+
+    expect(admin.describeConsumerGroups(EasyMock.eq(Collections.singletonList(group)), anyObject()))
+      .andReturn(describeGroupsResult(ConsumerGroupState.STABLE))
+      .once()
+    expect(admin.listConsumerGroupOffsets(EasyMock.eq(group), anyObject()))
+      .andReturn(listGroupOffsetsResult)
+      .once()
+    expect(admin.listOffsets(anyObject(), anyObject()))
+      .andAnswer(() => listOffsetsResult(getCurrentArguments.apply(0).asInstanceOf[util.Map[TopicPartition, OffsetSpec]]))
+      .once()
+    replay(admin)
+
+    val (state, assignments) = groupService.collectGroupOffsets(group)
+    assertEquals(Some("Stable"), state)
+    assertTrue(assignments.nonEmpty)
+    assertEquals(topicPartitions.size, assignments.get.size)
+  }
+
+  @Test
+  def testAdminRequestsForResetOffsets(): Unit = {
+    val args = Seq("--bootstrap-server", "localhost:9092", "--group", group, "--reset-offsets", "--to-latest")
+    val topicsWithoutPartitionsSpecified = topics.tail
+    val topicArgs = Seq("--topic", s"${topics.head}:${(0 until numPartitions).mkString(",")}") ++
+      topicsWithoutPartitionsSpecified.flatMap { topic => Seq("--topic", topic) }
+    val groupService = consumerGroupService((args ++ topicArgs).toArray)
+
+    expect(admin.describeConsumerGroups(EasyMock.eq(Collections.singletonList(group)), anyObject()))
+      .andReturn(describeGroupsResult(ConsumerGroupState.DEAD))
+      .once()
+    expect(admin.describeTopics(EasyMock.eq(topicsWithoutPartitionsSpecified.asJava), anyObject()))
+      .andReturn(describeTopicsResult)

Review comment:
       `describeTopicsResult` includes all topics but `topicsWithoutPartitionsSpecified` includes only `topics.tail`. Maybe it should return matched data.

##########
File path: core/src/test/scala/unit/kafka/admin/ConsumerGroupServiceTest.scala
##########
@@ -0,0 +1,133 @@
+/**
+ * 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.admin
+
+import java.util
+import java.util.{Collections, Optional}
+
+import kafka.admin.ConsumerGroupCommand.{ConsumerGroupCommandOptions, ConsumerGroupService}
+import org.apache.kafka.clients.admin._
+import org.apache.kafka.clients.consumer.{OffsetAndMetadata, RangeAssignor}
+import org.apache.kafka.common.{ConsumerGroupState, KafkaFuture, Node, TopicPartition, TopicPartitionInfo}
+import org.easymock.EasyMock
+import org.easymock.EasyMock._
+import org.junit.jupiter.api.Assertions.{assertEquals, assertTrue}
+import org.junit.jupiter.api.Test
+
+import scala.jdk.CollectionConverters._
+
+class ConsumerGroupServiceTest {
+
+  private val group = "testGroup"
+  private val topics = (0 until 5).map { i => s"testTopic$i" }
+  private val numPartitions = 10
+  private val topicPartitions = topics.flatMap { topic => (0 until numPartitions).map { i => new TopicPartition(topic, i) }}
+  private val admin: Admin = mock(classOf[Admin])
+
+  @Test
+  def testAdminRequestsForDescribeOffsets(): Unit = {
+    val args = Array("--bootstrap-server", "localhost:9092", "--group", group, "--describe", "--offsets")
+    val groupService = consumerGroupService(args)
+
+    expect(admin.describeConsumerGroups(EasyMock.eq(Collections.singletonList(group)), anyObject()))
+      .andReturn(describeGroupsResult(ConsumerGroupState.STABLE))
+      .once()
+    expect(admin.listConsumerGroupOffsets(EasyMock.eq(group), anyObject()))
+      .andReturn(listGroupOffsetsResult)
+      .once()
+    expect(admin.listOffsets(anyObject(), anyObject()))
+      .andAnswer(() => listOffsetsResult(getCurrentArguments.apply(0).asInstanceOf[util.Map[TopicPartition, OffsetSpec]]))
+      .once()
+    replay(admin)
+
+    val (state, assignments) = groupService.collectGroupOffsets(group)
+    assertEquals(Some("Stable"), state)
+    assertTrue(assignments.nonEmpty)
+    assertEquals(topicPartitions.size, assignments.get.size)
+  }
+
+  @Test
+  def testAdminRequestsForResetOffsets(): Unit = {
+    val args = Seq("--bootstrap-server", "localhost:9092", "--group", group, "--reset-offsets", "--to-latest")
+    val topicsWithoutPartitionsSpecified = topics.tail
+    val topicArgs = Seq("--topic", s"${topics.head}:${(0 until numPartitions).mkString(",")}") ++
+      topicsWithoutPartitionsSpecified.flatMap { topic => Seq("--topic", topic) }
+    val groupService = consumerGroupService((args ++ topicArgs).toArray)
+
+    expect(admin.describeConsumerGroups(EasyMock.eq(Collections.singletonList(group)), anyObject()))
+      .andReturn(describeGroupsResult(ConsumerGroupState.DEAD))
+      .once()
+    expect(admin.describeTopics(EasyMock.eq(topicsWithoutPartitionsSpecified.asJava), anyObject()))
+      .andReturn(describeTopicsResult)
+      .once()
+    expect(admin.listOffsets(anyObject(), anyObject()))
+      .andAnswer(() => listOffsetsResult(getCurrentArguments.apply(0).asInstanceOf[util.Map[TopicPartition, OffsetSpec]]))
+      .once()
+    replay(admin)
+
+    val resetResult = groupService.resetOffsets()
+    assertEquals(Set(group), resetResult.keySet)
+    assertEquals(topicPartitions.toSet, resetResult(group).keySet)
+  }
+
+  private def consumerGroupService(args: Array[String]): ConsumerGroupService = {
+    new ConsumerGroupService(new ConsumerGroupCommandOptions(args)) {
+      override protected def createAdminClient(configOverrides: collection.Map[String, String]): Admin = {
+        admin
+      }
+    }
+  }
+
+  private def describeGroupsResult(groupState: ConsumerGroupState): DescribeConsumerGroupsResult = {
+    val member1 = new MemberDescription("member1", Optional.of("instance1"), "client1", "host1", null)
+    val description = new ConsumerGroupDescription(group,
+      true,
+      Collections.singleton(member1),
+      classOf[RangeAssignor].getName,
+      groupState,
+      new Node(1, "localhost", 9092))
+    new DescribeConsumerGroupsResult(Collections.singletonMap(group, KafkaFuture.completedFuture(description)))
+  }
+
+  private def listGroupOffsetsResult: ListConsumerGroupOffsetsResult = {
+    val offsets = topicPartitions.map { tp => tp -> new OffsetAndMetadata(100) }.toMap.asJava
+    val result: ListConsumerGroupOffsetsResult = mock(classOf[ListConsumerGroupOffsetsResult])
+    expect(result.partitionsToOffsetAndMetadata()).andReturn(KafkaFuture.completedFuture(offsets)).anyTimes()
+    replay(result)
+    result
+  }
+
+  private def listOffsetsResult(partitions: util.Map[TopicPartition, OffsetSpec]): ListOffsetsResult = {
+    assertEquals(topicPartitions.toSet, partitions.keySet.asScala)
+    assertEquals(classOf[OffsetSpec.LatestSpec], partitions.values.iterator.next.getClass)
+    val resultInfo = new ListOffsetsResult.ListOffsetsResultInfo(100, System.currentTimeMillis, Optional.of(1))
+    val futures = topicPartitions.map { tp => tp -> KafkaFuture.completedFuture(resultInfo) }.toMap
+    new ListOffsetsResult(futures.asJava)
+  }
+
+  private def describeTopicsResult: DescribeTopicsResult = {
+    val result: DescribeTopicsResult = mock(classOf[DescribeTopicsResult])
+    val topicDescriptions = topics.map { topic =>

Review comment:
       We almost create whole response. Also, we define `anyTimes` for the mock object. Hence, maybe we can replace the mock object by true object. The benefit is that it won't cause error if we call other methods of `DescribeTopicsResult` in the future.

##########
File path: core/src/main/scala/kafka/admin/ConsumerGroupCommand.scala
##########
@@ -708,30 +711,35 @@ object ConsumerGroupCommand extends Logging {
       options.timeoutMs(t)
     }
 
-    private def parseTopicPartitionsToReset(groupId: String, topicArgs: Seq[String]): Seq[TopicPartition] = topicArgs.flatMap {
-      case topicArg if topicArg.contains(":") =>
-        val topicPartitions = topicArg.split(":")
+    private def parseTopicPartitionsToReset(topicArgs: Seq[String]): Seq[TopicPartition] = {
+      val (topicsWithPartitions, topics) = topicArgs.partition(_.contains(":"))
+      val specifiedPartitions = topicsWithPartitions.flatMap { arg =>
+        val topicPartitions = arg.split(":")

Review comment:
       How about using match pattern? 
   ```scala
           arg.split(":") match {
             case Array(topic, partitions) =>
               partitions.split(",").map(partition => new TopicPartition(topic, partition.toInt))
           }
   ```
   The benefit is that it can throw exception if length of `split(":")` is not equal to 2.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org