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 2020/12/19 10:43:06 UTC

[GitHub] [kafka] dengziming opened a new pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

dengziming opened a new pull request #9769:
URL: https://github.com/apache/kafka/pull/9769


   *More detailed description of your change*
   1. Add topicNames in `MetadataCache` and add alter `KafkaApis.handleTopicMetadataRequest` according to the KIP
   2. Add method `describeTopicsWithIds` in KafkaAdminClient, similar to `describeTopics`
   3. Change `DescribeTopicsResult` to `DescribeTopicsResult<T>`, which is a little different from the KIP
   
   *Summary of testing strategy (including rationale)*
   Test locally, here is some result:
   ```
   New server + new Client 
   --describe --zookeeper localhost:2181 --topic-id a-Paxi-LSka9sIVy9UFp_Q
   Exception in thread "main" java.lang.IllegalArgumentException: --topic-id can used only with --bootstrap-server
   
   --describe --bootstrap-server localhost:9092 --topic-id a-Paxi-LSka9sIVy9UFp_Q
   Topic: old-version-topic	TopicId: a-Paxi-LSka9sIVy9UFp_Q	PartitionCount: 2	ReplicationFactor: 1	Configs: segment.bytes=1073741824
   	Topic: old-version-topic	Partition: 0	Leader: 0	Replicas: 0	Isr: 0
   	Topic: old-version-topic	Partition: 1	Leader: 0	Replicas: 0	Isr: 0
   
   Old Server/ new Client
   --describe --bootstrap-server localhost:9092 --topic-id a-Paxi-LSka9sIVy9UFp_Q
   Error while executing topic command : TopicId a-Paxi-LSka9sIVy9UFp_Q not found.
   
   New server + old client
   --describe --bootstrap-server localhost:9092 --topic-id a-Paxi-LSka9sIVy9UFp_Q
   Exception in thread "main" joptsimple.UnrecognizedOptionException: topic-id is not a recognized option
   ```
   
   ### Committer Checklist (excluded from commit message)
   - [ ] Verify design and implementation 
   - [ ] Verify test coverage and CI build status
   - [ ] Verify documentation (including upgrade notes)
   


----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r680325822



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
##########
@@ -42,6 +34,14 @@
 import org.apache.kafka.common.quota.ClientQuotaFilter;
 import org.apache.kafka.common.requests.LeaveGroupResponse;
 
+import java.time.Duration;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;

Review comment:
       This is invoked by the IDE spotless plugin, but I think this is reasonable since we are going to add import order checkstyle here:https://github.com/apache/kafka/pull/10428/files#diff-49a96e7eea8a94af862798a45174e6ac43eb4f8b4bd40759b5da63ba31ec3ef7R615, and java.* will be put last.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] jolshan commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-870786796


   Hi again @dengziming. There was one more change to the API (should be the last one this time). It includes adding a new class that I implement in this PR: https://github.com/apache/kafka/pull/10892
   Please check out the KIP for more details on the changes to DescribeTopicsResult and the new apis for describing with topic IDs. Thanks for your diligence and patience with this one. 


-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r556568400



##########
File path: clients/src/test/java/org/apache/kafka/clients/admin/MockAdminClient.java
##########
@@ -206,6 +209,8 @@ synchronized public void addTopic(boolean internal,
                 logDirs.add(brokerLogDirs.get(partition.leader().id()).get(0));
             }
         }
+        Uuid topicId = Uuid.randomUuid();
+        topicIds.put(name, topicId);

Review comment:
       Yes, I add a method with a `usesTopicId` parameter.




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r677932361



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
##########
@@ -42,6 +34,14 @@
 import org.apache.kafka.common.quota.ClientQuotaFilter;
 import org.apache.kafka.common.requests.LeaveGroupResponse;
 
+import java.time.Duration;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;

Review comment:
       nit: is there a reason we moved these imports?




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] jolshan commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-764014519


   @dengziming I realized that for this, it really depends on the IBP of the controller. (That is, we need UpdateMetadata to send topic IDs to all the brokers). So maybe instead of checking IBP it would make sense to check if the MetadataCache does not have any topic IDs. What do you think?


----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-770763376


   @rajinisivaram I haven't run any system tests and I will try to run some system tests later. Should I run the 2 python script locally and analyze the logs?


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563955092



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       I think this usage is fine since we will only get here if use the topic name version of the request and the topic does not exist.




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r564664073



##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -313,42 +314,59 @@ object TopicCommand extends Logging {
     }
 
     override def describeTopic(opts: TopicCommandOptions): Unit = {
-      val topics = getTopics(opts.topic, opts.excludeInternalTopics)
-      ensureTopicExists(topics, opts.topic, !opts.ifExists)
+      // if topicId is provided and not zero, will use topicId regardless of topic name
+      val useTopicId = opts.topicId.map(Uuid.fromString).nonEmpty

Review comment:
       good point!




----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-770011022


   @dengziming Even the last PR build for this one seemed to have issues. I merged https://github.com/apache/kafka/pull/9684 first since that build looked good. But now this one needs a rebase. I can do the rebase if it is already too late for you. 


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r566222319



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1251,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, Uuid.ZERO_UUID, false, util.Collections.emptyList()))

Review comment:
       Looks good now. We will only get to this point with knownTopicNames, so the metadataCache will also have the topic ID. 👍 




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r664078161



##########
File path: core/src/main/scala/kafka/api/ApiVersion.scala
##########
@@ -116,7 +116,9 @@ object ApiVersion {
     // Introduce AllocateProducerIds (KIP-730)
     KAFKA_3_0_IV0,
     // Introduce ListOffsets V7 which supports listing offsets by max timestamp (KIP-734)
-    KAFKA_3_0_IV1
+    KAFKA_3_0_IV1,
+    // Introduced topic IDs to MetadataRequest

Review comment:
       Why are we bumping IBP? Metadata is not an inter-broker protocol, so I think bumping the metadata protocol suffices.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r546860091



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -31,29 +31,29 @@
  * The API of this class is evolving, see {@link Admin} for details.
  */
 @InterfaceStability.Evolving
-public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+public class DescribeTopicsResult<T> {

Review comment:
       I think this parameterization is a pretty good idea, and I can add it to my delete topics PR. But if we are going to change the public API, we should update the KIP and potentially update the mailing list with the changes. 




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563168372



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1190,8 +1192,31 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    // Check if topicId is presented firstly.
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
+    val supportedVersionTopicIds = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1) topicIds else Set.empty[Uuid]

Review comment:
       Hello, I tried to add 2 test in `MetadataRequestBetweenDifferentIbpTest` to verify these 2 cases, this test will take probably 10 seconds since we need to constantly restart brokers to change the controller.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r567719703



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1191,8 +1192,35 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    // Check if topicId is presented firstly.
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
+    val useTopicId = topicIds.nonEmpty
+
+    val (supportedVersionTopicIds, unsupportedVersionTopicIds) = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1)
+      (topicIds, Set.empty[Uuid])
+    else
+      (Set.empty[Uuid], topicIds)
+
+    val unsupportedVersionTopicMetadata = if (unsupportedVersionTopicIds.isEmpty)
+      Seq.empty[MetadataResponseTopic]
+    else
+      unsupportedVersionTopicIds.map(topicId =>
+        metadataResponseTopic(Errors.UNSUPPORTED_VERSION, null, topicId, false, util.Collections.emptyList())).toSeq
+
+    // Only get topicIds and topicNames when supporting topicId
+    val unknownTopicIds = supportedVersionTopicIds.filter(metadataCache.getTopicName(_).isEmpty)
+    val knownTopicNames = supportedVersionTopicIds.flatMap(metadataCache.getTopicName)
+
+    val unknownTopicIdsTopicMetadata = if (unknownTopicIds.isEmpty)

Review comment:
       Thanks, Done!




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r564639774



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1194,9 +1194,13 @@ class KafkaApis(val requestChannel: RequestChannel,
 
     // Check if topicId is presented firstly.
     val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
-    val supportedVersionTopicIds = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1) topicIds else Set.empty[Uuid]
 
-    val unsupportedVersionTopicIds = topicIds.diff(supportedVersionTopicIds)
+    val (supportedVersionTopicIds, unsupportedVersionTopicIds) = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1)
+      (topicIds, Set.empty[Uuid])
+    else
+      (Set.empty[Uuid], topicIds)
+
+    // val unsupportedVersionTopicIds = topicIds.diff(supportedVersionTopicIds)

Review comment:
       nit: remove commented out line.




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r664076833



##########
File path: clients/src/main/java/org/apache/kafka/common/requests/MetadataRequest.java
##########
@@ -65,6 +65,20 @@ public Builder(List<String> topics, boolean allowAutoTopicCreation) {
             this(topics, allowAutoTopicCreation, ApiKeys.METADATA.oldestVersion(),  ApiKeys.METADATA.latestVersion());
         }
 
+        public Builder(List<Uuid> topicIds) {
+            super(ApiKeys.METADATA, ApiKeys.METADATA.oldestVersion(), ApiKeys.METADATA.latestVersion());
+            MetadataRequestData data = new MetadataRequestData();
+            if (topicIds == null)
+                data.setTopics(null);
+            else {
+                topicIds.forEach(topicId -> data.topics().add(new MetadataRequestTopic().setTopicId(topicId).setName("")));

Review comment:
       Is there a reason this is setting the name to empty and not null? (or no name set at all?)




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r547021462



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -31,29 +31,29 @@
  * The API of this class is evolving, see {@link Admin} for details.
  */
 @InterfaceStability.Evolving
-public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+public class DescribeTopicsResult<T> {

Review comment:
       I first tried a new class `DescribeTopicsResultWithIds` and find it's almost the same as `DescribeTopicsResult`, so I just use parameterization. We only need to change `DescribeTopicsResult` to `DescribeTopicsResult<String>` when using old clients.




----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-769798261


   There are quite a few failures in the last PR build. Failures don't look related to this PR, rerunning the build.


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563870325



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1190,8 +1192,31 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    // Check if topicId is presented firstly.
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
+    val supportedVersionTopicIds = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1) topicIds else Set.empty[Uuid]
+
+    val unsupportedVersionTopicIds = topicIds.diff(supportedVersionTopicIds)

Review comment:
       I'm curious if this diff is needed. It seems that the above check will result in all topicIds being left out or all of them being included.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-764219186


   > https://github.com/apache/kafka/pull/9769#issuecomment-764014519
   
   @rajinisivaram @jolshan I also realized this, we add topicId in `MetadataCache` from IBP=2.8.1, so instead of using `config.usesTopicId` it would make sense to check `config.interBrokerProtocolVersion >= KAFKA_2_8_IV1`


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan edited a comment on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan edited a comment on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-766972011


   Thanks for the updates and all the hard work! I added a few comments. Mostly just questions for clarification.


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r546862700



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
##########
@@ -287,7 +288,23 @@ default DescribeTopicsResult describeTopics(Collection<String> topicNames) {
      * @param options    The options to use when describing the topic.
      * @return The DescribeTopicsResult.
      */
-    DescribeTopicsResult describeTopics(Collection<String> topicNames, DescribeTopicsOptions options);
+    DescribeTopicsResult<String> describeTopics(Collection<String> topicNames, DescribeTopicsOptions options);
+
+    /**
+     * Describe some topics in the cluster by their topicId, with the default options.
+     * <p>
+     * This is a convenience method for {@link #describeTopicsWithIds(Collection, DescribeTopicsOptions)} with
+     * default options. See the overload for more details.
+     *
+     * @param topicIds The topicIds of the topics to describe.
+     * @return The DescribeTopicsResult.
+     */
+    default DescribeTopicsResult<Uuid> describeTopicsWithIds(Collection<Uuid> topicIds) {
+        return describeTopicsWithIds(topicIds, new DescribeTopicsOptions());
+    }
+
+    DescribeTopicsResult<Uuid> describeTopicsWithIds(Collection<Uuid> topicIds, DescribeTopicsOptions options);

Review comment:
       nit: javadoc comment missing




----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-763996884


   @dengziming https://github.com/apache/kafka/pull/9814 has been merged, so this needs rebasing and the check for IBP. Thanks.


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r677933885



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -32,28 +34,87 @@
  */
 @InterfaceStability.Evolving
 public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+    private final Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures;
+    private final Map<String, KafkaFuture<TopicDescription>> nameFutures;
 
-    protected DescribeTopicsResult(Map<String, KafkaFuture<TopicDescription>> futures) {
-        this.futures = futures;
+    protected DescribeTopicsResult(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures, Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        if (topicIdFutures != null && nameFutures != null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be specified.");
+        if (topicIdFutures == null && nameFutures == null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be null.");
+        this.topicIdFutures = topicIdFutures;
+        this.nameFutures = nameFutures;
+    }
+
+    static DescribeTopicsResult ofTopicIds(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures) {
+        return new DescribeTopicsResult(topicIdFutures, null);
+    }
+
+    static DescribeTopicsResult ofTopicNames(Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        return new DescribeTopicsResult(null, nameFutures);
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicIdCollection
+     *
+     * @return a map from topic IDs to futures which can be used to check the status of
+     *         individual topics if the request used topic IDs, otherwise return null.
+     */
+    public Map<Uuid, KafkaFuture<TopicDescription>> topicIdValues() {
+        return topicIdFutures;
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicNameCollection
+     *
+     * @return a map from topic names to futures which can be used to check the status of
+     *         individual topics if the request used topic names, otherwise return null.
+     */
+    public Map<String, KafkaFuture<TopicDescription>> topicNameValues() {
+        return nameFutures;
     }
 
     /**
      * Return a map from topic names to futures which can be used to check the status of
      * individual topics.
      */
+    @Deprecated
     public Map<String, KafkaFuture<TopicDescription>> values() {
-        return futures;
+        return nameFutures;
     }
 
     /**
      * Return a future which succeeds only if all the topic descriptions succeed.
      */
+    @Deprecated
     public KafkaFuture<Map<String, TopicDescription>> all() {
-        return KafkaFuture.allOf(futures.values().toArray(new KafkaFuture[0])).
+        return all(nameFutures);
+    }
+
+    /**
+     * Return a future which succeeds only if all the topic descriptions succeed.
+     */
+    public KafkaFuture<Map<String, TopicDescription>> allTopicNames() {
+        return all(nameFutures);
+    }
+
+    /**
+     * Return a future which succeeds only if all the topic descriptions succeed.
+     */
+    public KafkaFuture<Map<Uuid, TopicDescription>> allTopicIds() {
+        return all(topicIdFutures);
+    }
+
+    /**
+     * Return a future which succeeds only if all the topic descriptions succeed.
+     */
+    private static <T> KafkaFuture<Map<T, TopicDescription>> all(Map<T, KafkaFuture<TopicDescription>> futures) {
+

Review comment:
       nit: extra space here




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] rajinisivaram commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563620794



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,117 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_2_8_IV1)

Review comment:
       Don't we need the config for the third broker?

##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,117 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_2_8_IV1)
+    )
+  }
+
+  @Test
+  def testTopicIdUnsupported(): Unit = {
+
+    val topic = "topic"
+
+    // Ensure controller version = KAFKA_2_8_IV1, and then create a topic
+    ensureControllerIn(Seq(1))
+    createTopic(topic,  Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    // We can get topicId from the controller
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), brokerSocketServer(1))
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+    assertNotEquals(Uuid.ZERO_UUID, topicId)
+    assertNotNull(topicId)
+
+    // Send request to a broker whose version=KAFKA_2_8_IV0
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(0))
+    assertEquals(Errors.UNSUPPORTED_VERSION, resp2.topicMetadata.iterator().next().error())
+  }
+
+  @Test
+  def testUnknownTopicId(): Unit = {
+
+    val topic = "topic"
+
+    // Kill controller and restart until broker 2 become controller
+    ensureControllerIn(Seq(1))
+    createTopic(topic, Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), brokerSocketServer(1))
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+
+    // We could still get topic metadata by topicId
+    val topicMetadata = sendMetadataRequest(new MetadataRequest(requestData(null, topicId), 10.toShort), brokerSocketServer(1))
+      .topicMetadata.iterator().next()
+    assertEquals(topicId, topicMetadata.topicId())
+    assertEquals(topic, topicMetadata.topic())
+
+    // Make the broker whose version=KAFKA_2_8_IV0 controller
+    ensureControllerIn(Seq(0))
+
+    // Restart the broker whose version=KAFKA_2_8_IV1, and the controller will send metadata request to it
+    killBroker(1)
+    restartDeadBrokers()
+
+    // Send request to a broker whose version=KAFKA_2_8_IV1
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(1))
+    assertEquals(Errors.UNKNOWN_TOPIC_ID, resp2.topicMetadata.iterator().next().error())
+  }
+
+  private def ensureControllerIn(brokerIds: Seq[Int]): Unit = {
+    while (!brokerIds.contains(controllerSocketServer.config.brokerId)) {
+      killBroker(controllerSocketServer.config.brokerId)

Review comment:
       Instead of restarting brokers, we could delete the controller node in ZK to force controller election. It doesn't guarantee that the expected broker id becomes the next controller, but it may still get there faster than broker restarts




----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r562233235



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/TopicDescription.java
##########
@@ -65,6 +65,19 @@ public TopicDescription(String name, boolean internal, List<TopicPartitionInfo>
         this(name, internal, partitions, Collections.emptySet());
     }
 
+    /**
+     * Create an instance with the specified parameters.
+     *
+     * @param name The topic name
+     * @param internal Whether the topic is internal to Kafka
+     * @param partitions A list of partitions where the index represents the partition id and the element contains
+     *                   leadership and replica information for that partition.
+     * @param topicId the topic id
+     */
+    public TopicDescription(String name, boolean internal, List<TopicPartitionInfo> partitions, Uuid topicId) {

Review comment:
       Do we really need this constructor in the public class? We could just use the one below?

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
##########
@@ -1822,6 +1829,88 @@ void handleFailure(Throwable throwable) {
         return new DescribeTopicsResult(new HashMap<>(topicFutures));
     }
 
+    @Override
+    public DescribeTopicsResultWithIds describeTopicsWithIds(Collection<Uuid> topicIds, DescribeTopicsOptions options) {
+
+        final Map<Uuid, KafkaFutureImpl<TopicDescription>> topicFutures = new HashMap<>(topicIds.size());
+        final List<Uuid> topicIdsList = new ArrayList<>();
+        for (Uuid topicId : topicIds) {
+            if (topicIdIsUnrepresentable(topicId)) {
+                KafkaFutureImpl<TopicDescription> future = new KafkaFutureImpl<>();
+                future.completeExceptionally(new InvalidTopicException("The given topic id '" +
+                        topicId + "' cannot be represented in a request."));
+                topicFutures.put(topicId, future);
+            } else if (!topicFutures.containsKey(topicId)) {
+                topicFutures.put(topicId, new KafkaFutureImpl<>());
+                topicIdsList.add(topicId);
+            }
+        }
+        final long now = time.milliseconds();
+        Call call = new Call("describeTopicsWithIds", calcDeadlineMs(now, options.timeoutMs()),
+                new LeastLoadedNodeProvider()) {
+
+            @Override
+            MetadataRequest.Builder createRequest(int timeoutMs) {
+                return new MetadataRequest.Builder(new MetadataRequestData()
+                        .setTopics(convertTopicIdsToMetadataRequestTopic(topicIdsList))
+                        .setAllowAutoTopicCreation(false)
+                        .setIncludeTopicAuthorizedOperations(options.includeAuthorizedOperations()));
+            }
+
+            @Override
+            void handleResponse(AbstractResponse abstractResponse) {
+                MetadataResponse response = (MetadataResponse) abstractResponse;
+                // Handle server responses for particular topics.
+                Cluster cluster = response.cluster();
+                Map<Uuid, Errors> errors = response.errorsByTopicId();
+                for (Map.Entry<Uuid, KafkaFutureImpl<TopicDescription>> entry : topicFutures.entrySet()) {
+                    Uuid topicId = entry.getKey();
+                    KafkaFutureImpl<TopicDescription> future = entry.getValue();
+
+                    String topicName = cluster.topicName(topicId);
+                    if (topicName == null) {
+                        future.completeExceptionally(new UnknownTopicIdException("TopicId " + topicId + " not found."));
+                        continue;
+                    }
+                    Errors topicError = errors.get(topicId);
+                    if (topicError != null) {
+                        future.completeExceptionally(topicError.exception());
+                        continue;
+                    }
+
+                    boolean isInternal = cluster.internalTopics().contains(topicName);
+                    List<PartitionInfo> partitionInfos = cluster.partitionsForTopic(topicName);
+                    List<TopicPartitionInfo> partitions = new ArrayList<>(partitionInfos.size());
+                    for (PartitionInfo partitionInfo : partitionInfos) {
+                        TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(
+                                partitionInfo.partition(), leader(partitionInfo), Arrays.asList(partitionInfo.replicas()),
+                                Arrays.asList(partitionInfo.inSyncReplicas()));
+                        partitions.add(topicPartitionInfo);
+                    }
+                    partitions.sort(Comparator.comparingInt(TopicPartitionInfo::partition));
+                    TopicDescription topicDescription = new TopicDescription(topicName, isInternal, partitions,
+                            validAclOperations(response.topicAuthorizedOperations(topicName).get()), topicId);
+                    future.complete(topicDescription);
+                }
+            }
+
+            private Node leader(PartitionInfo partitionInfo) {

Review comment:
       This could be shared with `describeTopics` as well?

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1190,8 +1192,31 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    // Check if topicId is presented firstly.
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
+    val supportedVersionTopicIds = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1) topicIds else Set.empty[Uuid]

Review comment:
       @jolshan Shouldn't we use `KAFKA_2_8_IV1` for `KafkaConfig.usesTopicId` and use that here?

##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -635,6 +650,11 @@ object TopicCommand extends Logging {
                          .withRequiredArg
                          .describedAs("topic")
                          .ofType(classOf[String])
+    private val topicIdOpt = parser.accepts("topic-id", "The topic-id to describe." +
+      "This is used only with --bootstrap-server option for manage topic.")

Review comment:
       for manage topic => `for describing topics`?

##########
File path: clients/src/main/java/org/apache/kafka/common/requests/MetadataResponse.java
##########
@@ -91,12 +91,31 @@ public int throttleTimeMs() {
     public Map<String, Errors> errors() {
         Map<String, Errors> errors = new HashMap<>();
         for (MetadataResponseTopic metadata : data.topics()) {
+            if (metadata.name() == null) {
+                throw new NullPointerException("Use errorsByTopicId() when manage topic using topic id");

Review comment:
       We should never get here through the public APIs right? We could use IllegalStateException.

##########
File path: clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
##########
@@ -350,7 +351,8 @@
     POSITION_OUT_OF_RANGE(
         99,
         "Requested position is not greater than or equal to zero, and less than the size of the snapshot.",
-        PositionOutOfRangeException::new);
+        PositionOutOfRangeException::new),
+    UNKNOWN_TOPIC_ID(100, "The topic ID dose not exist", UnknownTopicIdException::new);

Review comment:
       typo: `does`

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/TopicDescription.java
##########
@@ -79,6 +92,16 @@ public TopicDescription(String name, boolean internal, List<TopicPartitionInfo>
         this(name, internal, partitions, authorizedOperations, Uuid.ZERO_UUID);
     }
 
+    /**
+     * Create an instance with the specified parameters.
+     *
+     * @param name The topic name
+     * @param internal Whether the topic is internal to Kafka
+     * @param partitions A list of partitions where the index represents the partition id and the element contains
+     *                   leadership and replica information for that partition.
+     * @param authorizedOperations authorized operations for this topic, or null if this is not known.

Review comment:
       Looks like default is empty set rather than null?

##########
File path: clients/src/main/java/org/apache/kafka/common/requests/MetadataResponse.java
##########
@@ -91,12 +91,31 @@ public int throttleTimeMs() {
     public Map<String, Errors> errors() {
         Map<String, Errors> errors = new HashMap<>();
         for (MetadataResponseTopic metadata : data.topics()) {
+            if (metadata.name() == null) {
+                throw new NullPointerException("Use errorsByTopicId() when manage topic using topic id");
+            }
             if (metadata.errorCode() != Errors.NONE.code())
                 errors.put(metadata.name(), Errors.forCode(metadata.errorCode()));
         }
         return errors;
     }
 
+    /**
+     * Get a map of the topicIds which had metadata errors
+     * @return the map
+     */
+    public Map<Uuid, Errors> errorsByTopicId() {
+        Map<Uuid, Errors> errors = new HashMap<>();
+        for (MetadataResponseTopic metadata : data.topics()) {
+            if (metadata.topicId() == Uuid.ZERO_UUID) {
+                throw new NullPointerException("Use errors() when manage topic using topic name");

Review comment:
       As before, IllegalStateException?

##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -313,42 +313,57 @@ object TopicCommand extends Logging {
     }
 
     override def describeTopic(opts: TopicCommandOptions): Unit = {
-      val topics = getTopics(opts.topic, opts.excludeInternalTopics)
-      ensureTopicExists(topics, opts.topic, !opts.ifExists)
+      val topicId = opts.topicId.map(Uuid.fromString).filter(_ != Uuid.ZERO_UUID)
+      // if topicId is provided and not zero, will use topicId regardless of topic name

Review comment:
       we would fail if both are provided?

##########
File path: clients/src/main/java/org/apache/kafka/common/errors/UnknownTopicIdException.java
##########
@@ -0,0 +1,28 @@
+/*
+ * 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 org.apache.kafka.common.errors;
+
+public class UnknownTopicIdException extends ApiException {
+    private static final long serialVersionUID = 1L;
+    public UnknownTopicIdException() {
+        super();

Review comment:
       `super()` is implied, so we can just leave the method empty?

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
##########
@@ -1822,6 +1829,88 @@ void handleFailure(Throwable throwable) {
         return new DescribeTopicsResult(new HashMap<>(topicFutures));
     }
 
+    @Override
+    public DescribeTopicsResultWithIds describeTopicsWithIds(Collection<Uuid> topicIds, DescribeTopicsOptions options) {
+
+        final Map<Uuid, KafkaFutureImpl<TopicDescription>> topicFutures = new HashMap<>(topicIds.size());
+        final List<Uuid> topicIdsList = new ArrayList<>();
+        for (Uuid topicId : topicIds) {
+            if (topicIdIsUnrepresentable(topicId)) {
+                KafkaFutureImpl<TopicDescription> future = new KafkaFutureImpl<>();
+                future.completeExceptionally(new InvalidTopicException("The given topic id '" +
+                        topicId + "' cannot be represented in a request."));
+                topicFutures.put(topicId, future);
+            } else if (!topicFutures.containsKey(topicId)) {
+                topicFutures.put(topicId, new KafkaFutureImpl<>());
+                topicIdsList.add(topicId);
+            }
+        }
+        final long now = time.milliseconds();
+        Call call = new Call("describeTopicsWithIds", calcDeadlineMs(now, options.timeoutMs()),
+                new LeastLoadedNodeProvider()) {
+
+            @Override
+            MetadataRequest.Builder createRequest(int timeoutMs) {
+                return new MetadataRequest.Builder(new MetadataRequestData()
+                        .setTopics(convertTopicIdsToMetadataRequestTopic(topicIdsList))
+                        .setAllowAutoTopicCreation(false)
+                        .setIncludeTopicAuthorizedOperations(options.includeAuthorizedOperations()));
+            }
+
+            @Override
+            void handleResponse(AbstractResponse abstractResponse) {
+                MetadataResponse response = (MetadataResponse) abstractResponse;
+                // Handle server responses for particular topics.
+                Cluster cluster = response.cluster();
+                Map<Uuid, Errors> errors = response.errorsByTopicId();
+                for (Map.Entry<Uuid, KafkaFutureImpl<TopicDescription>> entry : topicFutures.entrySet()) {
+                    Uuid topicId = entry.getKey();
+                    KafkaFutureImpl<TopicDescription> future = entry.getValue();
+
+                    String topicName = cluster.topicName(topicId);
+                    if (topicName == null) {
+                        future.completeExceptionally(new UnknownTopicIdException("TopicId " + topicId + " not found."));
+                        continue;
+                    }
+                    Errors topicError = errors.get(topicId);
+                    if (topicError != null) {
+                        future.completeExceptionally(topicError.exception());
+                        continue;
+                    }
+
+                    boolean isInternal = cluster.internalTopics().contains(topicName);
+                    List<PartitionInfo> partitionInfos = cluster.partitionsForTopic(topicName);
+                    List<TopicPartitionInfo> partitions = new ArrayList<>(partitionInfos.size());
+                    for (PartitionInfo partitionInfo : partitionInfos) {
+                        TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(
+                                partitionInfo.partition(), leader(partitionInfo), Arrays.asList(partitionInfo.replicas()),
+                                Arrays.asList(partitionInfo.inSyncReplicas()));
+                        partitions.add(topicPartitionInfo);
+                    }
+                    partitions.sort(Comparator.comparingInt(TopicPartitionInfo::partition));
+                    TopicDescription topicDescription = new TopicDescription(topicName, isInternal, partitions,
+                            validAclOperations(response.topicAuthorizedOperations(topicName).get()), topicId);
+                    future.complete(topicDescription);

Review comment:
       Could we move the code shared between `describeTopics` and `describeTopicsWithIds` to a common private method?

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1190,8 +1192,31 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    // Check if topicId is presented firstly.
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
+    val supportedVersionTopicIds = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1) topicIds else Set.empty[Uuid]
+
+    val unSupportedVersionTopicIds = topicIds.diff(supportedVersionTopicIds)

Review comment:
       `unSupported` => `unsupported` since it is one word (below as well)

##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -313,42 +313,54 @@ object TopicCommand extends Logging {
     }
 
     override def describeTopic(opts: TopicCommandOptions): Unit = {
-      val topics = getTopics(opts.topic, opts.excludeInternalTopics)
-      ensureTopicExists(topics, opts.topic, !opts.ifExists)
+      val topicId = opts.topicId.map(Uuid.fromString).filter(_ != Uuid.ZERO_UUID)
+      val topics = if (topicId.isEmpty)
+        getTopics(opts.topic, opts.excludeInternalTopics)
+      else
+        Seq()
 
-      if (topics.nonEmpty) {
-        val allConfigs = adminClient.describeConfigs(topics.map(new ConfigResource(Type.TOPIC, _)).asJavaCollection).values()
-        val liveBrokers = adminClient.describeCluster().nodes().get().asScala.map(_.id())
-        val topicDescriptions = adminClient.describeTopics(topics.asJavaCollection).all().get().values().asScala
-        val describeOptions = new DescribeOptions(opts, liveBrokers.toSet)
-        val topicPartitions = topicDescriptions
-          .flatMap(td => td.partitions.iterator().asScala.map(p => new TopicPartition(td.name(), p.partition())))
-          .toSet.asJava
-        val reassignments = listAllReassignments(topicPartitions)
-
-        for (td <- topicDescriptions) {
-          val topicName = td.name
-          val topicId = td.topicId()
-          val config = allConfigs.get(new ConfigResource(Type.TOPIC, topicName)).get()
-          val sortedPartitions = td.partitions.asScala.sortBy(_.partition)
-
-          if (describeOptions.describeConfigs) {
-            val hasNonDefault = config.entries().asScala.exists(!_.isDefault)
-            if (!opts.reportOverriddenConfigs || hasNonDefault) {
-              val numPartitions = td.partitions().size
-              val firstPartition = td.partitions.iterator.next()
-              val reassignment = reassignments.get(new TopicPartition(td.name, firstPartition.partition))
-              val topicDesc = TopicDescription(topicName, topicId, numPartitions, getReplicationFactor(firstPartition, reassignment), config, markedForDeletion = false)
-              topicDesc.printDescription()
-            }
+      if (topicId.isEmpty)
+        ensureTopicExists(topics, opts.topic, !opts.ifExists)

Review comment:
       Since listTopics uses MetadataRequest, we just need to add topic ids from the MetadataResponse to TopicListing?




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563872705



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1247,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), false, util.Collections.emptyList()))

Review comment:
       Does this potentially acknowledge a topic exists if we give a valid id?




----------------------------------------------------------------
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



[GitHub] [kafka] satishd commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
satishd commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r564641591



##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -313,42 +314,59 @@ object TopicCommand extends Logging {
     }
 
     override def describeTopic(opts: TopicCommandOptions): Unit = {
-      val topics = getTopics(opts.topic, opts.excludeInternalTopics)
-      ensureTopicExists(topics, opts.topic, !opts.ifExists)
+      // if topicId is provided and not zero, will use topicId regardless of topic name
+      val useTopicId = opts.topicId.map(Uuid.fromString).nonEmpty

Review comment:
       Based on the above comment, does not it need to handle `UUID.ZERO_UUID` too?

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/TopicListing.java
##########
@@ -17,24 +17,36 @@
 
 package org.apache.kafka.clients.admin;
 
+import org.apache.kafka.common.Uuid;
+
 /**
  * A listing of a topic in the cluster.
  */
 public class TopicListing {
     private final String name;
+    private final Uuid topicId;
     private final boolean internal;
 
     /**
      * Create an instance with the specified parameters.
      *
      * @param name The topic name
+     * @param topicId The topic id.
      * @param internal Whether the topic is internal to Kafka
      */
-    public TopicListing(String name, boolean internal) {
+    public TopicListing(String name, Uuid topicId, boolean internal) {
+        this.topicId = topicId;
         this.name = name;
         this.internal = internal;
     }
 
+    /**
+     * The name of the topic.

Review comment:
       typo: should have been "The id ~~name~~ of the topic"




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-865491775


   Hi @dengziming thanks for the update. There are a few more minor changes to the KIP.
   One is that after some discussion with people more familiar with clients, it makes sense to remove the UNSUPPORTED_VERSION error and only return UNKNOWN_TOPIC_ID when the topic ID is not found on the broker. (See: https://issues.apache.org/jira/browse/KAFKA-12976)


-- 
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r677932954



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
##########
@@ -303,7 +303,33 @@ default DescribeTopicsResult describeTopics(Collection<String> topicNames) {
      * @param options    The options to use when describing the topic.
      * @return The DescribeTopicsResult.
      */
-    DescribeTopicsResult describeTopics(Collection<String> topicNames, DescribeTopicsOptions options);
+    default DescribeTopicsResult describeTopics(Collection<String> topicNames, DescribeTopicsOptions options) {
+        return describeTopics(TopicCollection.ofTopicNames(topicNames), options);
+    }
+
+    /**
+     * This is a convenience method for {@link #describeTopics(TopicCollection, DescribeTopicsOptions)}
+     * with default options. See the overload for more details.
+     * <p>
+     * When using topic IDs, this operation is supported by brokers with version 3.1.0 or higher.
+     *
+     * @param topics The topics to describe.
+     * @return The DescribeTopicsResult.
+     */
+    default DescribeTopicsResult describeTopics(TopicCollection topics) {
+        return describeTopics(topics, new DescribeTopicsOptions());
+    }
+
+    /**
+     * describe a batch of topics.

Review comment:
       Can we adjust this javadoc to be `Describe some topics in the cluster.` like the previous API?




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r665814181



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,103 @@
+/**
+  * 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.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_3_0_IV1}
+import kafka.network.SocketServer
+import kafka.utils.TestUtils
+import kafka.zk.ZkVersion
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_3_0_IV1),
+      createConfig(2, KAFKA_3_0_IV1)
+    )
+  }
+
+  @Test
+  def testUnknownTopicId(): Unit = {
+    val topic = "topic"
+
+    // Kill controller and restart until broker 2 become controller
+    ensureControllerIn(Seq(1, 2))
+    createTopic(topic, Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 12.toShort), controllerSocketServer)
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+
+    // We could still get topic metadata by topicId
+   val topicMetadata = sendMetadataRequest(new MetadataRequest(requestData(null, topicId), 12.toShort), controllerSocketServer)
+      .topicMetadata.iterator().next()
+    assertEquals(topicId, topicMetadata.topicId())
+    assertEquals(topic, topicMetadata.topic())
+
+    // Make the broker whose version=KAFKA_3_0_IV0 controller

Review comment:
       This class is created to test the 2 cases here: https://github.com/apache/kafka/pull/9769#discussion_r562511974 , and now we only need to test the `UNKNOWN_TOPIC_ID` case since we do not need `UNSUPPORTED_VERSION` now.
   
   And this comment is wrong, I will fix it.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] jolshan commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-887966371


   @dengziming -- @rajinisivaram can help in about 2 weeks. I will try to help review so it will be ready when she gets to it.


-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r566550612



##########
File path: core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
##########
@@ -1879,6 +1879,109 @@ class KafkaApisTest {
     assertTrue(response.topicsByError(Errors.UNKNOWN_TOPIC_OR_PARTITION).isEmpty)
   }
 
+  @Test
+  def testUnauthorizedTopicMetadataRequest(): Unit = {
+
+    // 1. Set up broker information
+    val plaintextListener = ListenerName.forSecurityProtocol(SecurityProtocol.PLAINTEXT)
+    val broker = new UpdateMetadataBroker()
+      .setId(0)
+      .setRack("rack")
+      .setEndpoints(Seq(
+        new UpdateMetadataEndpoint()
+          .setHost("broker0")
+          .setPort(9092)
+          .setSecurityProtocol(SecurityProtocol.PLAINTEXT.id)
+          .setListener(plaintextListener.value)
+      ).asJava)
+
+    // 2. Set up authorizer
+    val authorizer: Authorizer = EasyMock.niceMock(classOf[Authorizer])
+    val unauthorizedTopic = "unauthorized-topic"
+    val authorizedTopic = "authorized-topic"
+
+    val expectedActions = Seq(
+      new Action(AclOperation.DESCRIBE, new ResourcePattern(ResourceType.TOPIC, unauthorizedTopic, PatternType.LITERAL), 1, true, true),
+      new Action(AclOperation.DESCRIBE, new ResourcePattern(ResourceType.TOPIC, authorizedTopic, PatternType.LITERAL), 1, true, true)
+    )
+
+    val expectedAuthorizeResult = Seq(AuthorizationResult.DENIED, AuthorizationResult.ALLOWED).asJava
+
+    EasyMock.expect(authorizer.authorize(anyObject[RequestContext], EasyMock.eq(expectedActions.asJava)))
+      .andReturn(expectedAuthorizeResult)
+      .times(2)
+
+    // 3. Set up MetadataCache
+    val authorizedTopicId = Uuid.randomUuid();
+    val unauthorizedTopicId = Uuid.randomUuid();
+
+    val topicIds = new util.HashMap[String, Uuid]()
+    topicIds.put(authorizedTopic, authorizedTopicId)
+    topicIds.put(unauthorizedTopic, unauthorizedTopicId)
+
+    def createDummyPartitionStates(topic: String) = {
+      new UpdateMetadataPartitionState()
+        .setTopicName(topic)
+        .setPartitionIndex(0)
+        .setControllerEpoch(1)
+        .setLeader(0)
+        .setLeaderEpoch(1)
+        .setReplicas(Collections.singletonList(0))
+        .setZkVersion(0)
+        .setIsr(Collections.singletonList(0))
+    }
+
+    // Send UpdateMetadataReq to update MetadataCache
+    val partitionStates = Seq(unauthorizedTopic, authorizedTopic).map(createDummyPartitionStates)
+
+    val updateMetadataRequest = new UpdateMetadataRequest.Builder(ApiKeys.UPDATE_METADATA.latestVersion, 0,
+      0, 0, partitionStates.asJava, Seq(broker).asJava, topicIds).build()
+    metadataCache.updateMetadata(correlationId = 0, updateMetadataRequest)
+
+    // 4. Send TopicMetadataReq using topicId
+    val capturedMetadataByTopicIdResp = expectNoThrottling()
+    EasyMock.replay(clientRequestQuotaManager, requestChannel, authorizer)
+
+    val metadataReqByTopicId = new MetadataRequest.Builder(util.Arrays.asList(authorizedTopicId, unauthorizedTopicId)).build()
+    createKafkaApis(authorizer = Some(authorizer)).handleTopicMetadataRequest(buildRequest(metadataReqByTopicId, plaintextListener))
+    val metadataByTopicIdResp = readResponse(metadataReqByTopicId, capturedMetadataByTopicIdResp).asInstanceOf[MetadataResponse]
+
+    val metadataByTopicId = metadataByTopicIdResp.data().topics().asScala.groupBy(_.topicId()).view.mapValues(_.head).toMap

Review comment:
       Thank you, Done.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r556437337



##########
File path: clients/src/test/java/org/apache/kafka/clients/admin/MockAdminClient.java
##########
@@ -206,6 +209,8 @@ synchronized public void addTopic(boolean internal,
                 logDirs.add(brokerLogDirs.get(partition.leader().id()).get(0));
             }
         }
+        Uuid topicId = Uuid.randomUuid();
+        topicIds.put(name, topicId);

Review comment:
       Currently, MockAdminClient is mainly used in connect module and stream module, we could add another ticket to do this.   




----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-771541128


   @dengziming Thanks for looking into this. Looks like a timing issue. @jolshan had run two system test runs on this PR last week and both had these consumer issues. At the time trunk looked good. But last night's trunk run also had very similar set of failures. So there is clearly something going on that is not related to this PR. Will take a look today.


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563872442



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       Does this potentially leak the topic name when we are using topic IDs?

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       (and if we give ID when using name, we acknowledge it exists)




----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r566327327



##########
File path: core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
##########
@@ -1879,6 +1879,109 @@ class KafkaApisTest {
     assertTrue(response.topicsByError(Errors.UNKNOWN_TOPIC_OR_PARTITION).isEmpty)
   }
 
+  @Test
+  def testUnauthorizedTopicMetadataRequest(): Unit = {
+
+    // 1. Set up broker information
+    val plaintextListener = ListenerName.forSecurityProtocol(SecurityProtocol.PLAINTEXT)
+    val broker = new UpdateMetadataBroker()
+      .setId(0)
+      .setRack("rack")
+      .setEndpoints(Seq(
+        new UpdateMetadataEndpoint()
+          .setHost("broker0")
+          .setPort(9092)
+          .setSecurityProtocol(SecurityProtocol.PLAINTEXT.id)
+          .setListener(plaintextListener.value)
+      ).asJava)
+
+    // 2. Set up authorizer
+    val authorizer: Authorizer = EasyMock.niceMock(classOf[Authorizer])
+    val unauthorizedTopic = "unauthorized-topic"
+    val authorizedTopic = "authorized-topic"
+
+    val expectedActions = Seq(
+      new Action(AclOperation.DESCRIBE, new ResourcePattern(ResourceType.TOPIC, unauthorizedTopic, PatternType.LITERAL), 1, true, true),
+      new Action(AclOperation.DESCRIBE, new ResourcePattern(ResourceType.TOPIC, authorizedTopic, PatternType.LITERAL), 1, true, true)
+    )
+
+    val expectedAuthorizeResult = Seq(AuthorizationResult.DENIED, AuthorizationResult.ALLOWED).asJava
+
+    EasyMock.expect(authorizer.authorize(anyObject[RequestContext], EasyMock.eq(expectedActions.asJava)))
+      .andReturn(expectedAuthorizeResult)
+      .times(2)
+
+    // 3. Set up MetadataCache
+    val authorizedTopicId = Uuid.randomUuid();
+    val unauthorizedTopicId = Uuid.randomUuid();
+
+    val topicIds = new util.HashMap[String, Uuid]()
+    topicIds.put(authorizedTopic, authorizedTopicId)
+    topicIds.put(unauthorizedTopic, unauthorizedTopicId)
+
+    def createDummyPartitionStates(topic: String) = {
+      new UpdateMetadataPartitionState()
+        .setTopicName(topic)
+        .setPartitionIndex(0)
+        .setControllerEpoch(1)
+        .setLeader(0)
+        .setLeaderEpoch(1)
+        .setReplicas(Collections.singletonList(0))
+        .setZkVersion(0)
+        .setIsr(Collections.singletonList(0))
+    }
+
+    // Send UpdateMetadataReq to update MetadataCache
+    val partitionStates = Seq(unauthorizedTopic, authorizedTopic).map(createDummyPartitionStates)
+
+    val updateMetadataRequest = new UpdateMetadataRequest.Builder(ApiKeys.UPDATE_METADATA.latestVersion, 0,
+      0, 0, partitionStates.asJava, Seq(broker).asJava, topicIds).build()
+    metadataCache.updateMetadata(correlationId = 0, updateMetadataRequest)
+
+    // 4. Send TopicMetadataReq using topicId
+    val capturedMetadataByTopicIdResp = expectNoThrottling()
+    EasyMock.replay(clientRequestQuotaManager, requestChannel, authorizer)
+
+    val metadataReqByTopicId = new MetadataRequest.Builder(util.Arrays.asList(authorizedTopicId, unauthorizedTopicId)).build()
+    createKafkaApis(authorizer = Some(authorizer)).handleTopicMetadataRequest(buildRequest(metadataReqByTopicId, plaintextListener))
+    val metadataByTopicIdResp = readResponse(metadataReqByTopicId, capturedMetadataByTopicIdResp).asInstanceOf[MetadataResponse]
+
+    val metadataByTopicId = metadataByTopicIdResp.data().topics().asScala.groupBy(_.topicId()).view.mapValues(_.head).toMap

Review comment:
       @dengziming Thanks for the test! This line and the line declaring `metadataByTopicName` below are failing the scala 2.12 build, can we rewrite without `mapValues` so that the Java8/Scala2.12 build passes? Thanks.




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan edited a comment on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan edited a comment on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-772830472


   @dengziming I don't know if you saw the mailing list discussion on this KIP, but the summary is that I talked to Ismael offline and we thought it would be good to hold off on the Admin Client APIs until after the 2.8 release is cut. I mentioned in that thread about splitting this PR into two (one PR with Admin client changes, one with everything else), but on further thought, I think it makes sense to wait until after 2.8 is cut.


----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563708864



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,117 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_2_8_IV1)

Review comment:
       Firstly I add 2 brokers to ensure faster election after killing broker, now I added a broker since we need not kill broker to trigger election.




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563955092



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       I think we only care about authorizedForCreate when using topic names. but just want to make sure we don't give a name/id away




----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r565615638



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1251,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, Uuid.ZERO_UUID, false, util.Collections.emptyList()))

Review comment:
       Good point. If not authorized for describe when using topic ids, we need to make sure we don't return the topic or information about existence of a topic - i.e we can't return TOPIC_AUTHORIZATION_FAILED. Perhaps UNKNOWN_TOPIC_ID would be more suitable.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r556176373



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/TopicDescription.java
##########
@@ -62,25 +62,25 @@ public int hashCode() {
      *                   leadership and replica information for that partition.
      */
     public TopicDescription(String name, boolean internal, List<TopicPartitionInfo> partitions) {
-        this(name, internal, partitions, Collections.emptySet());
+        this(name, Uuid.ZERO_UUID, internal, partitions);
+    }
+
+    public TopicDescription(String name, Uuid topicId, boolean internal, List<TopicPartitionInfo> partitions) {
+        this(name, topicId, internal, partitions, Collections.emptySet());
     }
 
     /**
      * Create an instance with the specified parameters.
      *
      * @param name The topic name
+     * @param topicId the topic id
      * @param internal Whether the topic is internal to Kafka
      * @param partitions A list of partitions where the index represents the partition id and the element contains
      *                   leadership and replica information for that partition.
      * @param authorizedOperations authorized operations for this topic, or null if this is not known.
      */
-    public TopicDescription(String name, boolean internal, List<TopicPartitionInfo> partitions,
+    public TopicDescription(String name, Uuid topicId, boolean internal, List<TopicPartitionInfo> partitions,

Review comment:
       This is also my mistake, I tried to add a constructor but remove one, I have rollbacked the removing.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming removed a comment on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming removed a comment on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-770761700


   @rajinisivaram I haven't run any system tests  and I will try to run some system tests later.


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r565575532



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1251,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, Uuid.ZERO_UUID, false, util.Collections.emptyList()))

Review comment:
       So will we never reach this code path when using topic IDs? I think we are using topics to decide authorization. So in the case where we use ids and the name exists, then we will expose the name and return a zero ID?




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r680328486



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,102 @@
+/**
+  * 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.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_3_0_IV1}
+import kafka.network.SocketServer
+import kafka.utils.TestUtils
+import kafka.zk.ZkVersion
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_3_0_IV1),

Review comment:
       In fact, when I change this to KAFKA_3_1_IV0, this test became a flaky test, I think this may be related to the code about fetching by topicId you added previously, I see a log:"org.apache.kafka.common.errors.FetchSessionTopicIdException: The fetch session encountered inconsistent topic ID usage
   "  I am still investigating...
   
   Below is the exception throws you can also reproduce locally :
   [2021-07-31 16:15:29,658] WARN maxCnxns is not configured, using default value 0. (org.apache.zookeeper.server.ServerCnxnFactory:309)
     [2021-07-31 16:15:30,540] WARN No meta.properties file under dir /var/folders/xs/1lh3bwpj2674ch_3wyqbcv6c0000gn/T/kafka-3222035436551046976/meta.properties (kafka.server.BrokerMetadataCheckpoint:70)
     [2021-07-31 16:15:32,153] WARN Error while loading kafka-version.properties: null (org.apache.kafka.common.utils.AppInfoParser:46)
     [2021-07-31 16:15:32,270] WARN No meta.properties file under dir /var/folders/xs/1lh3bwpj2674ch_3wyqbcv6c0000gn/T/kafka-4473390687426195767/meta.properties (kafka.server.BrokerMetadataCheckpoint:70)
     [2021-07-31 16:15:32,620] WARN No meta.properties file under dir /var/folders/xs/1lh3bwpj2674ch_3wyqbcv6c0000gn/T/kafka-3222063565575329695/meta.properties (kafka.server.BrokerMetadataCheckpoint:70)
     [2021-07-31 16:15:34,739] WARN [Controller id=0] A controller has been elected but just resigned, this will result in another round of election (kafka.controller.KafkaController:72)
     org.apache.kafka.common.errors.ControllerMovedException: The ephemeral node at /controller went away while checking whether the controller election succeeds. Aborting controller startup procedure
     [2021-07-31 16:15:34,822] WARN [Controller id=2] A controller has been elected but just resigned, this will result in another round of election (kafka.controller.KafkaController:72)
     org.apache.kafka.common.errors.ControllerMovedException: Controller epoch zkVersion check fails. Expected zkVersion = 4
     [2021-07-31 16:15:35,087] WARN [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Error in response for fetch request (type=FetchRequest, replicaId=2, maxWait=500, minBytes=1, maxBytes=10485760, fetchData={}, isolationLevel=READ_UNCOMMITTED, toForget=, metadata=(sessionId=289640652, epoch=1), rackId=) (kafka.server.ReplicaFetcherThread:72)
     org.apache.kafka.common.errors.FetchSessionTopicIdException: The fetch session encountered inconsistent topic ID usage
     [2021-07-31 16:15:35,087] WARN [ReplicaFetcher replicaId=1, leaderId=2, fetcherId=0] Error in response for fetch request (type=FetchRequest, replicaId=1, maxWait=500, minBytes=1, maxBytes=10485760, fetchData={}, isolationLevel=READ_UNCOMMITTED, toForget=, metadata=(sessionId=125490650, epoch=1), rackId=) (kafka.server.ReplicaFetcherThread:72)
     org.apache.kafka.common.errors.FetchSessionTopicIdException: The fetch session encountered inconsistent topic ID usage
     [2021-07-31 16:15:50,273] WARN [KafkaServer id=2] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,273] WARN [KafkaServer id=0] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,277] WARN [KafkaServer id=1] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,383] WARN [KafkaServer id=0] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,384] WARN [KafkaServer id=2] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,386] WARN [KafkaServer id=1] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,493] WARN [KafkaServer id=2] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,495] WARN [KafkaServer id=1] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,495] WARN [KafkaServer id=0] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,526] WARN [KafkaServer id=2] Proceeding to do an unclean shutdown as all the controlled shutdown attempts failed (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,527] WARN [KafkaServer id=0] Proceeding to do an unclean shutdown as all the controlled shutdown attempts failed (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,526] WARN [KafkaServer id=1] Proceeding to do an unclean shutdown as all the controlled shutdown attempts failed (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,586] WARN [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Error in response for fetch request (type=FetchRequest, replicaId=2, maxWait=500, minBytes=1, maxBytes=10485760, fetchData={}, isolationLevel=READ_UNCOMMITTED, toForget=, metadata=(sessionId=297980525, epoch=27), rackId=) (kafka.server.ReplicaFetcherThread:72)
     java.io.IOException: Connection to 1 was disconnected before the response was read
     at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:99)
     at kafka.server.ReplicaFetcherBlockingSend.sendRequest(ReplicaFetcherBlockingSend.scala:109)
     at kafka.server.ReplicaFetcherThread.fetchFromLeader(ReplicaFetcherThread.scala:219)
     at kafka.server.AbstractFetcherThread.processFetchRequest(AbstractFetcherThread.scala:314)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3(AbstractFetcherThread.scala:137)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3$adapted(AbstractFetcherThread.scala:136)
     at scala.Option.foreach(Option.scala:437)
     at kafka.server.AbstractFetcherThread.maybeFetch(AbstractFetcherThread.scala:136)
     at kafka.server.AbstractFetcherThread.doWork(AbstractFetcherThread.scala:119)
     at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:96)
     [2021-07-31 16:15:50,587] WARN [ReplicaFetcher replicaId=0, leaderId=2, fetcherId=0] Error in response for fetch request (type=FetchRequest, replicaId=0, maxWait=500, minBytes=1, maxBytes=10485760, fetchData={}, isolationLevel=READ_UNCOMMITTED, toForget=, metadata=(sessionId=1654389138, epoch=30), rackId=) (kafka.server.ReplicaFetcherThread:72)
     java.io.IOException: Connection to 2 was disconnected before the response was read
     at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:99)
     at kafka.server.ReplicaFetcherBlockingSend.sendRequest(ReplicaFetcherBlockingSend.scala:109)
     at kafka.server.ReplicaFetcherThread.fetchFromLeader(ReplicaFetcherThread.scala:219)
     at kafka.server.AbstractFetcherThread.processFetchRequest(AbstractFetcherThread.scala:314)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3(AbstractFetcherThread.scala:137)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3$adapted(AbstractFetcherThread.scala:136)
     at scala.Option.foreach(Option.scala:437)
     at kafka.server.AbstractFetcherThread.maybeFetch(AbstractFetcherThread.scala:136)
     at kafka.server.AbstractFetcherThread.doWork(AbstractFetcherThread.scala:119)
     at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:96)
     [2021-07-31 16:15:50,587] WARN [ReplicaFetcher replicaId=1, leaderId=2, fetcherId=0] Error in response for fetch request (type=FetchRequest, replicaId=1, maxWait=500, minBytes=1, maxBytes=10485760, fetchData={}, isolationLevel=READ_UNCOMMITTED, toForget=, metadata=(sessionId=1562647001, epoch=27), rackId=) (kafka.server.ReplicaFetcherThread:72)
     java.io.IOException: Connection to 2 was disconnected before the response was read
     at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:99)
     at kafka.server.ReplicaFetcherBlockingSend.sendRequest(ReplicaFetcherBlockingSend.scala:109)
     at kafka.server.ReplicaFetcherThread.fetchFromLeader(ReplicaFetcherThread.scala:219)
     at kafka.server.AbstractFetcherThread.processFetchRequest(AbstractFetcherThread.scala:314)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3(AbstractFetcherThread.scala:137)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3$adapted(AbstractFetcherThread.scala:136)
     at scala.Option.foreach(Option.scala:437)
     at kafka.server.AbstractFetcherThread.maybeFetch(AbstractFetcherThread.scala:136)
     at kafka.server.AbstractFetcherThread.doWork(AbstractFetcherThread.scala:119)
     at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:96)
     [2021-07-31 16:15:50,587] WARN [ReplicaFetcher replicaId=0, leaderId=1, fetcherId=0] Error in response for fetch request (type=FetchRequest, replicaId=0, maxWait=500, minBytes=1, maxBytes=10485760, fetchData={}, isolationLevel=READ_UNCOMMITTED, toForget=, metadata=(sessionId=1980753179, epoch=30), rackId=) (kafka.server.ReplicaFetcherThread:72)
     java.io.IOException: Connection to 1 was disconnected before the response was read
     at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:99)
     at kafka.server.ReplicaFetcherBlockingSend.sendRequest(ReplicaFetcherBlockingSend.scala:109)
     at kafka.server.ReplicaFetcherThread.fetchFromLeader(ReplicaFetcherThread.scala:219)
     at kafka.server.AbstractFetcherThread.processFetchRequest(AbstractFetcherThread.scala:314)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3(AbstractFetcherThread.scala:137)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3$adapted(AbstractFetcherThread.scala:136)
     at scala.Option.foreach(Option.scala:437)
     at kafka.server.AbstractFetcherThread.maybeFetch(AbstractFetcherThread.scala:136)
     at kafka.server.AbstractFetcherThread.doWork(AbstractFetcherThread.scala:119)
     at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:96)
     [2021-07-31 16:15:51,480] WARN Unexpected exception (org.apache.zookeeper.server.NIOServerCnxn:364)
     EndOfStreamException: Unable to read additional data from client, it probably closed the socket: address = /127.0.0.1:62546, session = 0x1002345a02e0001
     at org.apache.zookeeper.server.NIOServerCnxn.handleFailedRead(NIOServerCnxn.java:163)
     at org.apache.zookeeper.server.NIOServerCnxn.doIO(NIOServerCnxn.java:326)
     at org.apache.zookeeper.server.NIOServerCnxnFactory$IOWorkRequest.doWork(NIOServerCnxnFactory.java:522)
     at org.apache.zookeeper.server.WorkerService$ScheduledWorkRequest.run(WorkerService.java:154)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
     at java.lang.Thread.run(Thread.java:748)
   
     org.opentest4j.AssertionFailedError: No controller broker is elected in time period
   
     at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)
     at org.junit.jupiter.api.Assertions.fail(Assertions.java:117)
     at kafka.server.MetadataRequestBetweenDifferentIbpTest.ensureControllerIn(MetadataRequestBetweenDifferentIbpTest.scala:78)
     at kafka.server.MetadataRequestBetweenDifferentIbpTest.testUnknownTopicId(MetadataRequestBetweenDifferentIbpTest.scala:62)
    
   




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r697535233



##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -568,6 +619,10 @@ object TopicCommand extends Logging {
         throw new IllegalArgumentException("--bootstrap-server must be specified")
       if (has(describeOpt) && has(ifExistsOpt))
         CommandLineUtils.checkRequiredArgs(parser, options, topicOpt)
+      if(has(describeOpt) && has(ifExistsOpt)) {
+        if (has(topicOpt) == has(topicIdOpt))

Review comment:
       Thank you for this reminding, I also fixed a bug when using --topic-id and --if-exists.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r562333723



##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -313,42 +313,57 @@ object TopicCommand extends Logging {
     }
 
     override def describeTopic(opts: TopicCommandOptions): Unit = {
-      val topics = getTopics(opts.topic, opts.excludeInternalTopics)
-      ensureTopicExists(topics, opts.topic, !opts.ifExists)
+      val topicId = opts.topicId.map(Uuid.fromString).filter(_ != Uuid.ZERO_UUID)
+      // if topicId is provided and not zero, will use topicId regardless of topic name

Review comment:
       that's what I thought at the beginning, now I think it's better to use topicId and print a warning message if both are provided.

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
##########
@@ -1822,6 +1829,88 @@ void handleFailure(Throwable throwable) {
         return new DescribeTopicsResult(new HashMap<>(topicFutures));
     }
 
+    @Override
+    public DescribeTopicsResultWithIds describeTopicsWithIds(Collection<Uuid> topicIds, DescribeTopicsOptions options) {
+
+        final Map<Uuid, KafkaFutureImpl<TopicDescription>> topicFutures = new HashMap<>(topicIds.size());
+        final List<Uuid> topicIdsList = new ArrayList<>();
+        for (Uuid topicId : topicIds) {
+            if (topicIdIsUnrepresentable(topicId)) {
+                KafkaFutureImpl<TopicDescription> future = new KafkaFutureImpl<>();
+                future.completeExceptionally(new InvalidTopicException("The given topic id '" +
+                        topicId + "' cannot be represented in a request."));
+                topicFutures.put(topicId, future);
+            } else if (!topicFutures.containsKey(topicId)) {
+                topicFutures.put(topicId, new KafkaFutureImpl<>());
+                topicIdsList.add(topicId);
+            }
+        }
+        final long now = time.milliseconds();
+        Call call = new Call("describeTopicsWithIds", calcDeadlineMs(now, options.timeoutMs()),
+                new LeastLoadedNodeProvider()) {
+
+            @Override
+            MetadataRequest.Builder createRequest(int timeoutMs) {
+                return new MetadataRequest.Builder(new MetadataRequestData()
+                        .setTopics(convertTopicIdsToMetadataRequestTopic(topicIdsList))
+                        .setAllowAutoTopicCreation(false)
+                        .setIncludeTopicAuthorizedOperations(options.includeAuthorizedOperations()));
+            }
+
+            @Override
+            void handleResponse(AbstractResponse abstractResponse) {
+                MetadataResponse response = (MetadataResponse) abstractResponse;
+                // Handle server responses for particular topics.
+                Cluster cluster = response.cluster();
+                Map<Uuid, Errors> errors = response.errorsByTopicId();
+                for (Map.Entry<Uuid, KafkaFutureImpl<TopicDescription>> entry : topicFutures.entrySet()) {
+                    Uuid topicId = entry.getKey();
+                    KafkaFutureImpl<TopicDescription> future = entry.getValue();
+
+                    String topicName = cluster.topicName(topicId);
+                    if (topicName == null) {
+                        future.completeExceptionally(new UnknownTopicIdException("TopicId " + topicId + " not found."));
+                        continue;
+                    }
+                    Errors topicError = errors.get(topicId);
+                    if (topicError != null) {
+                        future.completeExceptionally(topicError.exception());
+                        continue;
+                    }
+
+                    boolean isInternal = cluster.internalTopics().contains(topicName);
+                    List<PartitionInfo> partitionInfos = cluster.partitionsForTopic(topicName);
+                    List<TopicPartitionInfo> partitions = new ArrayList<>(partitionInfos.size());
+                    for (PartitionInfo partitionInfo : partitionInfos) {
+                        TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(
+                                partitionInfo.partition(), leader(partitionInfo), Arrays.asList(partitionInfo.replicas()),
+                                Arrays.asList(partitionInfo.inSyncReplicas()));
+                        partitions.add(topicPartitionInfo);
+                    }
+                    partitions.sort(Comparator.comparingInt(TopicPartitionInfo::partition));
+                    TopicDescription topicDescription = new TopicDescription(topicName, isInternal, partitions,
+                            validAclOperations(response.topicAuthorizedOperations(topicName).get()), topicId);
+                    future.complete(topicDescription);

Review comment:
       Thank you, I added a getTopicDescriptionFromCluster to do this.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r664306898



##########
File path: clients/src/main/resources/common/message/MetadataResponse.json
##########
@@ -65,7 +66,7 @@
       "about": "Each topic in the response.", "fields": [
       { "name": "ErrorCode", "type": "int16", "versions": "0+",
         "about": "The topic error, or 0 if there was no error." },
-      { "name": "Name", "type": "string", "versions": "0+", "mapKey": true, "entityType": "topicName",
+      { "name": "Name", "type": "string", "versions": "0+", "mapKey": true, "entityType": "topicName", "nullableVersions": "10+",

Review comment:
       Yes, this should be 12+




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r680328486



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,102 @@
+/**
+  * 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.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_3_0_IV1}
+import kafka.network.SocketServer
+import kafka.utils.TestUtils
+import kafka.zk.ZkVersion
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_3_0_IV1),

Review comment:
       In fact, when I first change this to KAFKA_3_1_IV0, this test became a flaky test, and now I fixed it.
   
   




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563894054



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,125 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import kafka.zk.ZkVersion
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_2_8_IV1),
+      createConfig(2, KAFKA_2_8_IV1)
+    )
+  }
+
+  @Test
+  def testTopicIdUnsupported(): Unit = {
+
+    val topic = "topic"
+
+    // Ensure controller version = KAFKA_2_8_IV1, and then create a topic
+    ensureControllerIn(Seq(1, 2))
+    createTopic(topic,  Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    // We can get topicId from the controller
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), controllerSocketServer)
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+    assertNotEquals(Uuid.ZERO_UUID, topicId)
+    assertNotNull(topicId)
+
+    // Send request to a broker whose version=KAFKA_2_8_IV0
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(0))
+    assertEquals(Errors.UNSUPPORTED_VERSION, resp2.topicMetadata.iterator().next().error())
+  }
+
+  @Test
+  def testUnknownTopicId(): Unit = {
+
+    val topic = "topic"
+
+    // Kill controller and restart until broker 2 become controller
+    ensureControllerIn(Seq(1, 2))
+    createTopic(topic, Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), controllerSocketServer)
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+
+    // We could still get topic metadata by topicId
+    val topicMetadata = sendMetadataRequest(new MetadataRequest(requestData(null, topicId), 10.toShort), controllerSocketServer)
+      .topicMetadata.iterator().next()
+    assertEquals(topicId, topicMetadata.topicId())
+    assertEquals(topic, topicMetadata.topic())
+
+    // Make the broker whose version=KAFKA_2_8_IV0 controller
+    ensureControllerIn(Seq(0))
+
+    // Restart the broker whose version=KAFKA_2_8_IV1, and the controller will send metadata request to it
+    killBroker(1)
+    restartDeadBrokers()
+
+    // Send request to a broker whose version=KAFKA_2_8_IV1 and restarted just now
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(1))
+    assertEquals(Errors.UNKNOWN_TOPIC_ID, resp2.topicMetadata.iterator().next().error())

Review comment:
       This scenario is a bit of a corner case and maybe not a huge deal either way, but does it make more sense to respond with UNKNOWN_TOPIC_ID or UNSUPPORTED_VERSION here? Maybe either is fine since we can expect UNKNOWN_TOPIC_ID or UNSUPPORTED_VERSION during an upgrade like this anyway.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-772956211


   @rajinisivaram @jolshan , Thank you for your effort, I pay attention to the 2.8 release and update this pr.


----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r697217671



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -32,28 +34,86 @@
  */
 @InterfaceStability.Evolving
 public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+    private final Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures;
+    private final Map<String, KafkaFuture<TopicDescription>> nameFutures;
 
-    protected DescribeTopicsResult(Map<String, KafkaFuture<TopicDescription>> futures) {

Review comment:
       Since this is a protected method in a public API, we should probably keep the method and deprecate. It can just invoke the method below.

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -32,28 +34,86 @@
  */
 @InterfaceStability.Evolving
 public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+    private final Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures;
+    private final Map<String, KafkaFuture<TopicDescription>> nameFutures;
 
-    protected DescribeTopicsResult(Map<String, KafkaFuture<TopicDescription>> futures) {
-        this.futures = futures;
+    protected DescribeTopicsResult(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures, Map<String, KafkaFuture<TopicDescription>> nameFutures) {

Review comment:
       Make this package-private?

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1222,16 +1238,23 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
+      // Set topicId to zero since we will never create topic which topicId
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, Uuid.ZERO_UUID, isInternal(topic), util.Collections.emptyList()))
 
     // do not disclose the existence of topics unauthorized for Describe, so we've not even checked if they exist or not
     val unauthorizedForDescribeTopicMetadata =
       // In case of all topics, don't include topics unauthorized for Describe
       if ((requestVersion == 0 && (metadataRequest.topics == null || metadataRequest.topics.isEmpty)) || metadataRequest.isAllTopics)
         Set.empty[MetadataResponseTopic]
-      else
+      else if (useTopicId) {
+        // Topic IDs are not considered sensitive information, so we TOPIC_AUTHORIZATION_FAILED is OK

Review comment:
       `we` => returning?

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/TopicListing.java
##########
@@ -17,24 +17,36 @@
 
 package org.apache.kafka.clients.admin;
 
+import org.apache.kafka.common.Uuid;
+
 /**
  * A listing of a topic in the cluster.
  */
 public class TopicListing {
     private final String name;
+    private final Uuid topicId;
     private final boolean internal;
 
     /**
      * Create an instance with the specified parameters.
      *
      * @param name The topic name
+     * @param topicId The topic id.
      * @param internal Whether the topic is internal to Kafka
      */
-    public TopicListing(String name, boolean internal) {
+    public TopicListing(String name, Uuid topicId, boolean internal) {

Review comment:
       Since this is part of the public API, we should keep the original constructor and deprecate.

##########
File path: clients/src/main/java/org/apache/kafka/common/requests/MetadataResponse.java
##########
@@ -91,12 +91,31 @@ public int throttleTimeMs() {
     public Map<String, Errors> errors() {
         Map<String, Errors> errors = new HashMap<>();
         for (MetadataResponseTopic metadata : data.topics()) {
+            if (metadata.name() == null) {
+                throw new IllegalStateException("Use errorsByTopicId() when manage topic using topic id");
+            }
             if (metadata.errorCode() != Errors.NONE.code())
                 errors.put(metadata.name(), Errors.forCode(metadata.errorCode()));
         }
         return errors;
     }
 
+    /**
+     * Get a map of the topicIds which had metadata errors
+     * @return the map
+     */
+    public Map<Uuid, Errors> errorsByTopicId() {
+        Map<Uuid, Errors> errors = new HashMap<>();
+        for (MetadataResponseTopic metadata : data.topics()) {
+            if (metadata.topicId() == Uuid.ZERO_UUID) {
+                throw new IllegalStateException("Use errors() when manage topic using topic name");

Review comment:
       As before, `when manage` =>`when managing`

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -32,28 +34,86 @@
  */
 @InterfaceStability.Evolving
 public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+    private final Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures;
+    private final Map<String, KafkaFuture<TopicDescription>> nameFutures;
 
-    protected DescribeTopicsResult(Map<String, KafkaFuture<TopicDescription>> futures) {
-        this.futures = futures;
+    protected DescribeTopicsResult(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures, Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        if (topicIdFutures != null && nameFutures != null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be specified.");
+        if (topicIdFutures == null && nameFutures == null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be null.");
+        this.topicIdFutures = topicIdFutures;
+        this.nameFutures = nameFutures;
+    }
+
+    static DescribeTopicsResult ofTopicIds(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures) {
+        return new DescribeTopicsResult(topicIdFutures, null);
+    }
+
+    static DescribeTopicsResult ofTopicNames(Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        return new DescribeTopicsResult(null, nameFutures);
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicIdCollection
+     *
+     * @return a map from topic IDs to futures which can be used to check the status of
+     *         individual topics if the request used topic IDs, otherwise return null.
+     */
+    public Map<Uuid, KafkaFuture<TopicDescription>> topicIdValues() {
+        return topicIdFutures;
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicNameCollection
+     *
+     * @return a map from topic names to futures which can be used to check the status of
+     *         individual topics if the request used topic names, otherwise return null.
+     */
+    public Map<String, KafkaFuture<TopicDescription>> topicNameValues() {
+        return nameFutures;
     }
 
     /**
      * Return a map from topic names to futures which can be used to check the status of
      * individual topics.
      */
+    @Deprecated
     public Map<String, KafkaFuture<TopicDescription>> values() {
-        return futures;
+        return nameFutures;
     }
 
     /**
      * Return a future which succeeds only if all the topic descriptions succeed.
      */
+    @Deprecated

Review comment:
       Can we add ` @deprecated Since 3.1. Use xxx` in the javadoc above?

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -32,28 +34,86 @@
  */
 @InterfaceStability.Evolving
 public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+    private final Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures;
+    private final Map<String, KafkaFuture<TopicDescription>> nameFutures;
 
-    protected DescribeTopicsResult(Map<String, KafkaFuture<TopicDescription>> futures) {
-        this.futures = futures;
+    protected DescribeTopicsResult(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures, Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        if (topicIdFutures != null && nameFutures != null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be specified.");
+        if (topicIdFutures == null && nameFutures == null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be null.");
+        this.topicIdFutures = topicIdFutures;
+        this.nameFutures = nameFutures;
+    }
+
+    static DescribeTopicsResult ofTopicIds(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures) {
+        return new DescribeTopicsResult(topicIdFutures, null);
+    }
+
+    static DescribeTopicsResult ofTopicNames(Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        return new DescribeTopicsResult(null, nameFutures);
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicIdCollection
+     *
+     * @return a map from topic IDs to futures which can be used to check the status of
+     *         individual topics if the request used topic IDs, otherwise return null.
+     */
+    public Map<Uuid, KafkaFuture<TopicDescription>> topicIdValues() {
+        return topicIdFutures;
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicNameCollection
+     *
+     * @return a map from topic names to futures which can be used to check the status of
+     *         individual topics if the request used topic names, otherwise return null.
+     */
+    public Map<String, KafkaFuture<TopicDescription>> topicNameValues() {
+        return nameFutures;
     }
 
     /**
      * Return a map from topic names to futures which can be used to check the status of
      * individual topics.
      */
+    @Deprecated

Review comment:
       Can we add ` @deprecated Since 3.1. Use xxx` in the javadoc above?

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -32,28 +34,86 @@
  */
 @InterfaceStability.Evolving
 public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+    private final Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures;
+    private final Map<String, KafkaFuture<TopicDescription>> nameFutures;
 
-    protected DescribeTopicsResult(Map<String, KafkaFuture<TopicDescription>> futures) {
-        this.futures = futures;
+    protected DescribeTopicsResult(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures, Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        if (topicIdFutures != null && nameFutures != null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be specified.");
+        if (topicIdFutures == null && nameFutures == null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be null.");
+        this.topicIdFutures = topicIdFutures;
+        this.nameFutures = nameFutures;
+    }
+
+    static DescribeTopicsResult ofTopicIds(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures) {
+        return new DescribeTopicsResult(topicIdFutures, null);
+    }
+
+    static DescribeTopicsResult ofTopicNames(Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        return new DescribeTopicsResult(null, nameFutures);
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicIdCollection
+     *
+     * @return a map from topic IDs to futures which can be used to check the status of
+     *         individual topics if the request used topic IDs, otherwise return null.
+     */
+    public Map<Uuid, KafkaFuture<TopicDescription>> topicIdValues() {
+        return topicIdFutures;
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicNameCollection
+     *
+     * @return a map from topic names to futures which can be used to check the status of
+     *         individual topics if the request used topic names, otherwise return null.
+     */
+    public Map<String, KafkaFuture<TopicDescription>> topicNameValues() {
+        return nameFutures;
     }
 
     /**
      * Return a map from topic names to futures which can be used to check the status of
      * individual topics.
      */
+    @Deprecated
     public Map<String, KafkaFuture<TopicDescription>> values() {
-        return futures;
+        return nameFutures;
     }
 
     /**
      * Return a future which succeeds only if all the topic descriptions succeed.
      */
+    @Deprecated
     public KafkaFuture<Map<String, TopicDescription>> all() {
-        return KafkaFuture.allOf(futures.values().toArray(new KafkaFuture[0])).
+        return all(nameFutures);
+    }
+
+    /**
+     * Return a future which succeeds only if all the topic descriptions succeed.

Review comment:
       Also mention that this returns by topic name if the request used topic names. otherwise returns null.

##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -568,6 +619,10 @@ object TopicCommand extends Logging {
         throw new IllegalArgumentException("--bootstrap-server must be specified")
       if (has(describeOpt) && has(ifExistsOpt))
         CommandLineUtils.checkRequiredArgs(parser, options, topicOpt)
+      if(has(describeOpt) && has(ifExistsOpt)) {
+        if (has(topicOpt) == has(topicIdOpt))

Review comment:
       Should this be `&&` since the error below refers to both being specified? And should there an error for both not being specified?

##########
File path: clients/src/main/java/org/apache/kafka/common/requests/MetadataResponse.java
##########
@@ -91,12 +91,31 @@ public int throttleTimeMs() {
     public Map<String, Errors> errors() {
         Map<String, Errors> errors = new HashMap<>();
         for (MetadataResponseTopic metadata : data.topics()) {
+            if (metadata.name() == null) {
+                throw new IllegalStateException("Use errorsByTopicId() when manage topic using topic id");

Review comment:
       `when manage` => `when managing`

##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -568,6 +619,10 @@ object TopicCommand extends Logging {
         throw new IllegalArgumentException("--bootstrap-server must be specified")
       if (has(describeOpt) && has(ifExistsOpt))
         CommandLineUtils.checkRequiredArgs(parser, options, topicOpt)
+      if(has(describeOpt) && has(ifExistsOpt)) {
+        if (has(topicOpt) == has(topicIdOpt))
+          println("Only topic id will be used when both --topic and --topic-id are specified and topicId is not UUID.ZERO_UUID")

Review comment:
       Maybe just say `ZERO_UUID` (Or change case to `Uuid`




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r697531725



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -32,28 +34,86 @@
  */
 @InterfaceStability.Evolving
 public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+    private final Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures;
+    private final Map<String, KafkaFuture<TopicDescription>> nameFutures;
 
-    protected DescribeTopicsResult(Map<String, KafkaFuture<TopicDescription>> futures) {
-        this.futures = futures;
+    protected DescribeTopicsResult(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures, Map<String, KafkaFuture<TopicDescription>> nameFutures) {

Review comment:
       This is used in `InternalTopicManagerTest` so it should be protected, I just add a "VisibleForTesting" comment to it.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r546861997



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -31,29 +31,29 @@
  * The API of this class is evolving, see {@link Admin} for details.
  */
 @InterfaceStability.Evolving
-public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+public class DescribeTopicsResult<T> {

Review comment:
       I'm also curious what implications there are for changing the original DescribeTopicsResult when using old clients.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r664306577



##########
File path: core/src/main/scala/kafka/api/ApiVersion.scala
##########
@@ -116,7 +116,9 @@ object ApiVersion {
     // Introduce AllocateProducerIds (KIP-730)
     KAFKA_3_0_IV0,
     // Introduce ListOffsets V7 which supports listing offsets by max timestamp (KIP-734)
-    KAFKA_3_0_IV1
+    KAFKA_3_0_IV1,
+    // Introduced topic IDs to MetadataRequest

Review comment:
       You are right, we no longer need to check UNSUPPORTED_VERSION_ERROR, so it's unnecessary to bump IBP.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-770761700


   @rajinisivaram I haven't run any system tests  and I will try to run some system tests later.


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r677933885



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -32,28 +34,87 @@
  */
 @InterfaceStability.Evolving
 public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+    private final Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures;
+    private final Map<String, KafkaFuture<TopicDescription>> nameFutures;
 
-    protected DescribeTopicsResult(Map<String, KafkaFuture<TopicDescription>> futures) {
-        this.futures = futures;
+    protected DescribeTopicsResult(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures, Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        if (topicIdFutures != null && nameFutures != null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be specified.");
+        if (topicIdFutures == null && nameFutures == null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be null.");
+        this.topicIdFutures = topicIdFutures;
+        this.nameFutures = nameFutures;
+    }
+
+    static DescribeTopicsResult ofTopicIds(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures) {
+        return new DescribeTopicsResult(topicIdFutures, null);
+    }
+
+    static DescribeTopicsResult ofTopicNames(Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        return new DescribeTopicsResult(null, nameFutures);
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicIdCollection
+     *
+     * @return a map from topic IDs to futures which can be used to check the status of
+     *         individual topics if the request used topic IDs, otherwise return null.
+     */
+    public Map<Uuid, KafkaFuture<TopicDescription>> topicIdValues() {
+        return topicIdFutures;
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicNameCollection
+     *
+     * @return a map from topic names to futures which can be used to check the status of
+     *         individual topics if the request used topic names, otherwise return null.
+     */
+    public Map<String, KafkaFuture<TopicDescription>> topicNameValues() {
+        return nameFutures;
     }
 
     /**
      * Return a map from topic names to futures which can be used to check the status of
      * individual topics.
      */
+    @Deprecated
     public Map<String, KafkaFuture<TopicDescription>> values() {
-        return futures;
+        return nameFutures;
     }
 
     /**
      * Return a future which succeeds only if all the topic descriptions succeed.
      */
+    @Deprecated
     public KafkaFuture<Map<String, TopicDescription>> all() {
-        return KafkaFuture.allOf(futures.values().toArray(new KafkaFuture[0])).
+        return all(nameFutures);
+    }
+
+    /**
+     * Return a future which succeeds only if all the topic descriptions succeed.
+     */
+    public KafkaFuture<Map<String, TopicDescription>> allTopicNames() {
+        return all(nameFutures);
+    }
+
+    /**
+     * Return a future which succeeds only if all the topic descriptions succeed.
+     */
+    public KafkaFuture<Map<Uuid, TopicDescription>> allTopicIds() {
+        return all(topicIdFutures);
+    }
+
+    /**
+     * Return a future which succeeds only if all the topic descriptions succeed.
+     */
+    private static <T> KafkaFuture<Map<T, TopicDescription>> all(Map<T, KafkaFuture<TopicDescription>> futures) {
+

Review comment:
       nit: extra newline here




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] jolshan edited a comment on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan edited a comment on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-766972011


   Thanks for the updates and all the hard work! I added a few comments. Mostly just questions for clarification.


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r665476219



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
##########
@@ -303,7 +303,33 @@ default DescribeTopicsResult describeTopics(Collection<String> topicNames) {
      * @param options    The options to use when describing the topic.
      * @return The DescribeTopicsResult.
      */
-    DescribeTopicsResult describeTopics(Collection<String> topicNames, DescribeTopicsOptions options);
+    default DescribeTopicsResult describeTopics(Collection<String> topicNames, DescribeTopicsOptions options) {
+        return describeTopics(TopicCollection.ofTopicNames(topicNames), options);
+    }
+
+    /**
+     * This is a convenience method for {@link #describeTopics(TopicCollection, DescribeTopicsOptions)}
+     * with default options. See the overload for more details.
+     * <p>
+     * When using topic IDs, this operation is supported by brokers with version 3.0.0 or higher.
+     *
+     * @param topics The topics to delete.
+     * @return The DescribeTopicsResult.
+     */
+    default DescribeTopicsResult describeTopics(TopicCollection topics) {
+        return describeTopics(topics, new DescribeTopicsOptions());
+    }
+
+    /**
+     * describe a batch of topics.
+     *
+     * When using topic IDs, this operation is supported by brokers with version 3.0.0 or higher.

Review comment:
       Since we are past the feature freeze date, I think this will need to be 3.1 now. Same above.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r556176649



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
##########
@@ -1816,7 +1823,103 @@ void handleFailure(Throwable throwable) {
         if (!topicNamesList.isEmpty()) {
             runnable.call(call, now);
         }
-        return new DescribeTopicsResult(new HashMap<>(topicFutures));
+        return new DescribeTopicsResult<>(new HashMap<>(topicFutures));
+    }
+
+    @Override
+    public DescribeTopicsResult<Uuid> describeTopicsWithIds(Collection<Uuid> topicIds, DescribeTopicsOptions options) {
+
+        final Map<Uuid, KafkaFutureImpl<TopicDescription>> topicFutures = new HashMap<>(topicIds.size());
+        final List<Uuid> topicIdsList = new ArrayList<>();
+        for (Uuid topicId : topicIds) {
+            if (topicIdIsUnrepresentable(topicId)) {
+                KafkaFutureImpl<TopicDescription> future = new KafkaFutureImpl<>();
+                future.completeExceptionally(new InvalidTopicException("The given topic id '" +
+                        topicId + "' cannot be represented in a request."));
+                topicFutures.put(topicId, future);
+            } else if (!topicFutures.containsKey(topicId)) {
+                topicFutures.put(topicId, new KafkaFutureImpl<>());
+                topicIdsList.add(topicId);
+            }
+        }
+        final long now = time.milliseconds();
+        Call call = new Call("describeTopicsWithIds", calcDeadlineMs(now, options.timeoutMs()),
+                new LeastLoadedNodeProvider()) {
+
+            private boolean supportsDisablingTopicCreation = true;
+
+            @Override
+            MetadataRequest.Builder createRequest(int timeoutMs) {
+                if (supportsDisablingTopicCreation)
+                    return new MetadataRequest.Builder(new MetadataRequestData()
+                            .setTopics(convertTopicIdsToMetadataRequestTopic(topicIdsList))
+                            .setAllowAutoTopicCreation(false)
+                            .setIncludeTopicAuthorizedOperations(options.includeAuthorizedOperations()));
+                else
+                    return MetadataRequest.Builder.allTopics();
+            }
+
+            @Override
+            void handleResponse(AbstractResponse abstractResponse) {
+                MetadataResponse response = (MetadataResponse) abstractResponse;
+                // Handle server responses for particular topics.
+                Cluster cluster = response.cluster();
+                Map<String, Errors> errors = response.errors();
+                for (Map.Entry<Uuid, KafkaFutureImpl<TopicDescription>> entry : topicFutures.entrySet()) {
+                    Uuid topicId = entry.getKey();
+                    KafkaFutureImpl<TopicDescription> future = entry.getValue();
+
+                    String topicName = cluster.topicName(topicId);
+                    if (topicName == null) {
+                        future.completeExceptionally(new UnknownTopicIdException("TopicId " + topicId + " not found."));
+                        continue;
+                    }
+                    Errors topicError = errors.get(topicName);
+                    if (topicError != null) {
+                        future.completeExceptionally(topicError.exception());
+                        continue;
+                    }
+
+                    boolean isInternal = cluster.internalTopics().contains(topicName);
+                    List<PartitionInfo> partitionInfos = cluster.partitionsForTopic(topicName);
+                    List<TopicPartitionInfo> partitions = new ArrayList<>(partitionInfos.size());
+                    for (PartitionInfo partitionInfo : partitionInfos) {
+                        TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(
+                                partitionInfo.partition(), leader(partitionInfo), Arrays.asList(partitionInfo.replicas()),
+                                Arrays.asList(partitionInfo.inSyncReplicas()));
+                        partitions.add(topicPartitionInfo);
+                    }
+                    partitions.sort(Comparator.comparingInt(TopicPartitionInfo::partition));
+                    TopicDescription topicDescription = new TopicDescription(topicName, topicId, isInternal, partitions,
+                            validAclOperations(response.topicAuthorizedOperations(topicName).get()));
+                    future.complete(topicDescription);
+                }
+            }
+
+            private Node leader(PartitionInfo partitionInfo) {
+                if (partitionInfo.leader() == null || partitionInfo.leader().id() == Node.noNode().id())
+                    return null;
+                return partitionInfo.leader();
+            }
+
+            @Override
+            boolean handleUnsupportedVersionException(UnsupportedVersionException exception) {
+                if (supportsDisablingTopicCreation) {
+                    supportsDisablingTopicCreation = false;

Review comment:
       Sorry, just removing those code and using default implement.




----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram edited a comment on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram edited a comment on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-769894936


   @dengziming The new PR build completed and we are still seeing NullPointerException in the JDK 8 build for the new test. The results are here: https://ci-builds.apache.org/job/Kafka/job/kafka-pr/job/PR-9769/16/#showFailuresLink


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r546292513



##########
File path: clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
##########
@@ -343,7 +344,8 @@
     INVALID_UPDATE_VERSION(95, "The given update version was invalid.", InvalidUpdateVersionException::new),
     FEATURE_UPDATE_FAILED(96, "Unable to update finalized features due to an unexpected server error.", FeatureUpdateFailedException::new),
     PRINCIPAL_DESERIALIZATION_FAILURE(97, "Request principal deserialization failed during forwarding. " +
-         "This indicates an internal error on the broker cluster security setup.", PrincipalDeserializationException::new);
+         "This indicates an internal error on the broker cluster security setup.", PrincipalDeserializationException::new),
+    UNKNOWN_TOPIC_ID(98, "The topic ID dose not exist", UnknownTopicIdException::new);

Review comment:
       nit: typo "dose" -> "does" I also had a slightly different message in my PR that implements this error. Either one is fine. https://github.com/apache/kafka/pull/9684/files




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r565938411



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       @jolshan , Thank you, I misunderstood your comments before, I added the following changes:
   1. If we are using topicId in metadataReq, we set topicName=null and error=UNKNOWN_TOPIC_ID on unauthorized error
   2. If we are using topicName in metadataReq, we set topicId=ZERO and error=TOPIC_AUTHORIZATION_FAILED on unauthorized error.
   3. Add a unit test for the above 2 cases.
   @rajinisivaram @jolshan , pleas take a look.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r680328486



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,102 @@
+/**
+  * 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.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_3_0_IV1}
+import kafka.network.SocketServer
+import kafka.utils.TestUtils
+import kafka.zk.ZkVersion
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_3_0_IV1),

Review comment:
       In fact, when I change this to KAFKA_3_1_IV0, this test became a flaky test, I think this may be related to the code about fetch by topicId you added previously, I am still investigating.
   below is the exception throws:
   [2021-07-31 16:15:29,658] WARN maxCnxns is not configured, using default value 0. (org.apache.zookeeper.server.ServerCnxnFactory:309)
     [2021-07-31 16:15:30,540] WARN No meta.properties file under dir /var/folders/xs/1lh3bwpj2674ch_3wyqbcv6c0000gn/T/kafka-3222035436551046976/meta.properties (kafka.server.BrokerMetadataCheckpoint:70)
     [2021-07-31 16:15:32,153] WARN Error while loading kafka-version.properties: null (org.apache.kafka.common.utils.AppInfoParser:46)
     [2021-07-31 16:15:32,270] WARN No meta.properties file under dir /var/folders/xs/1lh3bwpj2674ch_3wyqbcv6c0000gn/T/kafka-4473390687426195767/meta.properties (kafka.server.BrokerMetadataCheckpoint:70)
     [2021-07-31 16:15:32,620] WARN No meta.properties file under dir /var/folders/xs/1lh3bwpj2674ch_3wyqbcv6c0000gn/T/kafka-3222063565575329695/meta.properties (kafka.server.BrokerMetadataCheckpoint:70)
     [2021-07-31 16:15:34,739] WARN [Controller id=0] A controller has been elected but just resigned, this will result in another round of election (kafka.controller.KafkaController:72)
     org.apache.kafka.common.errors.ControllerMovedException: The ephemeral node at /controller went away while checking whether the controller election succeeds. Aborting controller startup procedure
     [2021-07-31 16:15:34,822] WARN [Controller id=2] A controller has been elected but just resigned, this will result in another round of election (kafka.controller.KafkaController:72)
     org.apache.kafka.common.errors.ControllerMovedException: Controller epoch zkVersion check fails. Expected zkVersion = 4
     [2021-07-31 16:15:35,087] WARN [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Error in response for fetch request (type=FetchRequest, replicaId=2, maxWait=500, minBytes=1, maxBytes=10485760, fetchData={}, isolationLevel=READ_UNCOMMITTED, toForget=, metadata=(sessionId=289640652, epoch=1), rackId=) (kafka.server.ReplicaFetcherThread:72)
     org.apache.kafka.common.errors.FetchSessionTopicIdException: The fetch session encountered inconsistent topic ID usage
     [2021-07-31 16:15:35,087] WARN [ReplicaFetcher replicaId=1, leaderId=2, fetcherId=0] Error in response for fetch request (type=FetchRequest, replicaId=1, maxWait=500, minBytes=1, maxBytes=10485760, fetchData={}, isolationLevel=READ_UNCOMMITTED, toForget=, metadata=(sessionId=125490650, epoch=1), rackId=) (kafka.server.ReplicaFetcherThread:72)
     org.apache.kafka.common.errors.FetchSessionTopicIdException: The fetch session encountered inconsistent topic ID usage
     [2021-07-31 16:15:50,273] WARN [KafkaServer id=2] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,273] WARN [KafkaServer id=0] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,277] WARN [KafkaServer id=1] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,383] WARN [KafkaServer id=0] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,384] WARN [KafkaServer id=2] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,386] WARN [KafkaServer id=1] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,493] WARN [KafkaServer id=2] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,495] WARN [KafkaServer id=1] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,495] WARN [KafkaServer id=0] Retrying controlled shutdown after the previous attempt failed... (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,526] WARN [KafkaServer id=2] Proceeding to do an unclean shutdown as all the controlled shutdown attempts failed (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,527] WARN [KafkaServer id=0] Proceeding to do an unclean shutdown as all the controlled shutdown attempts failed (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,526] WARN [KafkaServer id=1] Proceeding to do an unclean shutdown as all the controlled shutdown attempts failed (kafka.server.KafkaServer:70)
     [2021-07-31 16:15:50,586] WARN [ReplicaFetcher replicaId=2, leaderId=1, fetcherId=0] Error in response for fetch request (type=FetchRequest, replicaId=2, maxWait=500, minBytes=1, maxBytes=10485760, fetchData={}, isolationLevel=READ_UNCOMMITTED, toForget=, metadata=(sessionId=297980525, epoch=27), rackId=) (kafka.server.ReplicaFetcherThread:72)
     java.io.IOException: Connection to 1 was disconnected before the response was read
     at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:99)
     at kafka.server.ReplicaFetcherBlockingSend.sendRequest(ReplicaFetcherBlockingSend.scala:109)
     at kafka.server.ReplicaFetcherThread.fetchFromLeader(ReplicaFetcherThread.scala:219)
     at kafka.server.AbstractFetcherThread.processFetchRequest(AbstractFetcherThread.scala:314)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3(AbstractFetcherThread.scala:137)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3$adapted(AbstractFetcherThread.scala:136)
     at scala.Option.foreach(Option.scala:437)
     at kafka.server.AbstractFetcherThread.maybeFetch(AbstractFetcherThread.scala:136)
     at kafka.server.AbstractFetcherThread.doWork(AbstractFetcherThread.scala:119)
     at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:96)
     [2021-07-31 16:15:50,587] WARN [ReplicaFetcher replicaId=0, leaderId=2, fetcherId=0] Error in response for fetch request (type=FetchRequest, replicaId=0, maxWait=500, minBytes=1, maxBytes=10485760, fetchData={}, isolationLevel=READ_UNCOMMITTED, toForget=, metadata=(sessionId=1654389138, epoch=30), rackId=) (kafka.server.ReplicaFetcherThread:72)
     java.io.IOException: Connection to 2 was disconnected before the response was read
     at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:99)
     at kafka.server.ReplicaFetcherBlockingSend.sendRequest(ReplicaFetcherBlockingSend.scala:109)
     at kafka.server.ReplicaFetcherThread.fetchFromLeader(ReplicaFetcherThread.scala:219)
     at kafka.server.AbstractFetcherThread.processFetchRequest(AbstractFetcherThread.scala:314)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3(AbstractFetcherThread.scala:137)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3$adapted(AbstractFetcherThread.scala:136)
     at scala.Option.foreach(Option.scala:437)
     at kafka.server.AbstractFetcherThread.maybeFetch(AbstractFetcherThread.scala:136)
     at kafka.server.AbstractFetcherThread.doWork(AbstractFetcherThread.scala:119)
     at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:96)
     [2021-07-31 16:15:50,587] WARN [ReplicaFetcher replicaId=1, leaderId=2, fetcherId=0] Error in response for fetch request (type=FetchRequest, replicaId=1, maxWait=500, minBytes=1, maxBytes=10485760, fetchData={}, isolationLevel=READ_UNCOMMITTED, toForget=, metadata=(sessionId=1562647001, epoch=27), rackId=) (kafka.server.ReplicaFetcherThread:72)
     java.io.IOException: Connection to 2 was disconnected before the response was read
     at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:99)
     at kafka.server.ReplicaFetcherBlockingSend.sendRequest(ReplicaFetcherBlockingSend.scala:109)
     at kafka.server.ReplicaFetcherThread.fetchFromLeader(ReplicaFetcherThread.scala:219)
     at kafka.server.AbstractFetcherThread.processFetchRequest(AbstractFetcherThread.scala:314)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3(AbstractFetcherThread.scala:137)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3$adapted(AbstractFetcherThread.scala:136)
     at scala.Option.foreach(Option.scala:437)
     at kafka.server.AbstractFetcherThread.maybeFetch(AbstractFetcherThread.scala:136)
     at kafka.server.AbstractFetcherThread.doWork(AbstractFetcherThread.scala:119)
     at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:96)
     [2021-07-31 16:15:50,587] WARN [ReplicaFetcher replicaId=0, leaderId=1, fetcherId=0] Error in response for fetch request (type=FetchRequest, replicaId=0, maxWait=500, minBytes=1, maxBytes=10485760, fetchData={}, isolationLevel=READ_UNCOMMITTED, toForget=, metadata=(sessionId=1980753179, epoch=30), rackId=) (kafka.server.ReplicaFetcherThread:72)
     java.io.IOException: Connection to 1 was disconnected before the response was read
     at org.apache.kafka.clients.NetworkClientUtils.sendAndReceive(NetworkClientUtils.java:99)
     at kafka.server.ReplicaFetcherBlockingSend.sendRequest(ReplicaFetcherBlockingSend.scala:109)
     at kafka.server.ReplicaFetcherThread.fetchFromLeader(ReplicaFetcherThread.scala:219)
     at kafka.server.AbstractFetcherThread.processFetchRequest(AbstractFetcherThread.scala:314)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3(AbstractFetcherThread.scala:137)
     at kafka.server.AbstractFetcherThread.$anonfun$maybeFetch$3$adapted(AbstractFetcherThread.scala:136)
     at scala.Option.foreach(Option.scala:437)
     at kafka.server.AbstractFetcherThread.maybeFetch(AbstractFetcherThread.scala:136)
     at kafka.server.AbstractFetcherThread.doWork(AbstractFetcherThread.scala:119)
     at kafka.utils.ShutdownableThread.run(ShutdownableThread.scala:96)
     [2021-07-31 16:15:51,480] WARN Unexpected exception (org.apache.zookeeper.server.NIOServerCnxn:364)
     EndOfStreamException: Unable to read additional data from client, it probably closed the socket: address = /127.0.0.1:62546, session = 0x1002345a02e0001
     at org.apache.zookeeper.server.NIOServerCnxn.handleFailedRead(NIOServerCnxn.java:163)
     at org.apache.zookeeper.server.NIOServerCnxn.doIO(NIOServerCnxn.java:326)
     at org.apache.zookeeper.server.NIOServerCnxnFactory$IOWorkRequest.doWork(NIOServerCnxnFactory.java:522)
     at org.apache.zookeeper.server.WorkerService$ScheduledWorkRequest.run(WorkerService.java:154)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
     at java.lang.Thread.run(Thread.java:748)
   
     org.opentest4j.AssertionFailedError: No controller broker is elected in time period
   
     at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)
     at org.junit.jupiter.api.Assertions.fail(Assertions.java:117)
     at kafka.server.MetadataRequestBetweenDifferentIbpTest.ensureControllerIn(MetadataRequestBetweenDifferentIbpTest.scala:78)
     at kafka.server.MetadataRequestBetweenDifferentIbpTest.testUnknownTopicId(MetadataRequestBetweenDifferentIbpTest.scala:62)
    
   




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r680401984



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,102 @@
+/**
+  * 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.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_3_0_IV1}
+import kafka.network.SocketServer
+import kafka.utils.TestUtils
+import kafka.zk.ZkVersion
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_3_0_IV1),

Review comment:
       Ah ok. There were some issues with KAFKA_3_1_IV0. I fixed one of the issues that led to flaky tests. Hopefully that helped this too.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r664309847



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -32,28 +34,87 @@
  */
 @InterfaceStability.Evolving
 public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+    private final Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures;
+    private final Map<String, KafkaFuture<TopicDescription>> nameFutures;
 
-    protected DescribeTopicsResult(Map<String, KafkaFuture<TopicDescription>> futures) {
-        this.futures = futures;
+    protected DescribeTopicsResult(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures, Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        if (topicIdFutures != null && nameFutures != null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be specified.");
+        if (topicIdFutures == null && nameFutures == null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be null.");
+        this.topicIdFutures = topicIdFutures;
+        this.nameFutures = nameFutures;
+    }
+
+    static DescribeTopicsResult ofTopicIds(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures) {
+        return new DescribeTopicsResult(topicIdFutures, null);
+    }
+
+    static DescribeTopicsResult ofTopicNames(Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        return new DescribeTopicsResult(null, nameFutures);
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicIdCollection
+     *
+     * @return a map from topic IDs to futures which can be used to check the status of
+     *         individual topics if the request used topic IDs, otherwise return null.
+     */
+    public Map<Uuid, KafkaFuture<TopicDescription>> topicIdValues() {
+        return topicIdFutures;
     }
 
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicNameCollection
+     *
+     * @return a map from topic names to futures which can be used to check the status of
+     *         individual topics if the request used topic names, otherwise return null.
+     */
+    public Map<String, KafkaFuture<TopicDescription>> topicNameValues() {
+        return nameFutures;
+    }
+
+
     /**
      * Return a map from topic names to futures which can be used to check the status of
      * individual topics.
      */
+    @Deprecated
     public Map<String, KafkaFuture<TopicDescription>> values() {
-        return futures;
+        return nameFutures;
     }
 
     /**
      * Return a future which succeeds only if all the topic descriptions succeed.
      */
     public KafkaFuture<Map<String, TopicDescription>> all() {
-        return KafkaFuture.allOf(futures.values().toArray(new KafkaFuture[0])).
+        return all(nameFutures);

Review comment:
       Done, and also change all usages to use `allTopicNames()`.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r566227520



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       LGTM




----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-769894936


   @dengziming The new PR build completed and we are still seeing NullPointerException in the JDK 8 build for the new test.


----------------------------------------------------------------
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



[GitHub] [kafka] dengziming edited a comment on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming edited a comment on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-770140196


   The 2 failures in https://ci-builds.apache.org/job/Kafka/job/kafka-pr/job/PR-9769/22/#showFailuresLink seem to be related to Mockito, maybe #10006 will fix it. @rajinisivaram PTAL.


----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-770724994


   @dengziming Have you tried any system tests with this PR? @jolshan ran a system tests build on this branch twice and found quite a few tests had failed. It is not clear whether the failures are due to the PR, but we haven't been seeing the same failures on other builds. If you have time to investigate, you can try running the DEV_BRANCH version of `tests/kafkatest/sanity_checks/test_performance_services.py` or the various compatibility tests in `tests/kafkatest/tests/client/client_compatibility_produce_consume_test.py`. 


----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r562233235



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/TopicDescription.java
##########
@@ -65,6 +65,19 @@ public TopicDescription(String name, boolean internal, List<TopicPartitionInfo>
         this(name, internal, partitions, Collections.emptySet());
     }
 
+    /**
+     * Create an instance with the specified parameters.
+     *
+     * @param name The topic name
+     * @param internal Whether the topic is internal to Kafka
+     * @param partitions A list of partitions where the index represents the partition id and the element contains
+     *                   leadership and replica information for that partition.
+     * @param topicId the topic id
+     */
+    public TopicDescription(String name, boolean internal, List<TopicPartitionInfo> partitions, Uuid topicId) {

Review comment:
       Do we really need this constructor in the public class? We could just use the one below?

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
##########
@@ -1822,6 +1829,88 @@ void handleFailure(Throwable throwable) {
         return new DescribeTopicsResult(new HashMap<>(topicFutures));
     }
 
+    @Override
+    public DescribeTopicsResultWithIds describeTopicsWithIds(Collection<Uuid> topicIds, DescribeTopicsOptions options) {
+
+        final Map<Uuid, KafkaFutureImpl<TopicDescription>> topicFutures = new HashMap<>(topicIds.size());
+        final List<Uuid> topicIdsList = new ArrayList<>();
+        for (Uuid topicId : topicIds) {
+            if (topicIdIsUnrepresentable(topicId)) {
+                KafkaFutureImpl<TopicDescription> future = new KafkaFutureImpl<>();
+                future.completeExceptionally(new InvalidTopicException("The given topic id '" +
+                        topicId + "' cannot be represented in a request."));
+                topicFutures.put(topicId, future);
+            } else if (!topicFutures.containsKey(topicId)) {
+                topicFutures.put(topicId, new KafkaFutureImpl<>());
+                topicIdsList.add(topicId);
+            }
+        }
+        final long now = time.milliseconds();
+        Call call = new Call("describeTopicsWithIds", calcDeadlineMs(now, options.timeoutMs()),
+                new LeastLoadedNodeProvider()) {
+
+            @Override
+            MetadataRequest.Builder createRequest(int timeoutMs) {
+                return new MetadataRequest.Builder(new MetadataRequestData()
+                        .setTopics(convertTopicIdsToMetadataRequestTopic(topicIdsList))
+                        .setAllowAutoTopicCreation(false)
+                        .setIncludeTopicAuthorizedOperations(options.includeAuthorizedOperations()));
+            }
+
+            @Override
+            void handleResponse(AbstractResponse abstractResponse) {
+                MetadataResponse response = (MetadataResponse) abstractResponse;
+                // Handle server responses for particular topics.
+                Cluster cluster = response.cluster();
+                Map<Uuid, Errors> errors = response.errorsByTopicId();
+                for (Map.Entry<Uuid, KafkaFutureImpl<TopicDescription>> entry : topicFutures.entrySet()) {
+                    Uuid topicId = entry.getKey();
+                    KafkaFutureImpl<TopicDescription> future = entry.getValue();
+
+                    String topicName = cluster.topicName(topicId);
+                    if (topicName == null) {
+                        future.completeExceptionally(new UnknownTopicIdException("TopicId " + topicId + " not found."));
+                        continue;
+                    }
+                    Errors topicError = errors.get(topicId);
+                    if (topicError != null) {
+                        future.completeExceptionally(topicError.exception());
+                        continue;
+                    }
+
+                    boolean isInternal = cluster.internalTopics().contains(topicName);
+                    List<PartitionInfo> partitionInfos = cluster.partitionsForTopic(topicName);
+                    List<TopicPartitionInfo> partitions = new ArrayList<>(partitionInfos.size());
+                    for (PartitionInfo partitionInfo : partitionInfos) {
+                        TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(
+                                partitionInfo.partition(), leader(partitionInfo), Arrays.asList(partitionInfo.replicas()),
+                                Arrays.asList(partitionInfo.inSyncReplicas()));
+                        partitions.add(topicPartitionInfo);
+                    }
+                    partitions.sort(Comparator.comparingInt(TopicPartitionInfo::partition));
+                    TopicDescription topicDescription = new TopicDescription(topicName, isInternal, partitions,
+                            validAclOperations(response.topicAuthorizedOperations(topicName).get()), topicId);
+                    future.complete(topicDescription);
+                }
+            }
+
+            private Node leader(PartitionInfo partitionInfo) {

Review comment:
       This could be shared with `describeTopics` as well?

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1190,8 +1192,31 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    // Check if topicId is presented firstly.
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
+    val supportedVersionTopicIds = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1) topicIds else Set.empty[Uuid]

Review comment:
       @jolshan Shouldn't we use `KAFKA_2_8_IV1` for `KafkaConfig.usesTopicId` and use that here?

##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -635,6 +650,11 @@ object TopicCommand extends Logging {
                          .withRequiredArg
                          .describedAs("topic")
                          .ofType(classOf[String])
+    private val topicIdOpt = parser.accepts("topic-id", "The topic-id to describe." +
+      "This is used only with --bootstrap-server option for manage topic.")

Review comment:
       for manage topic => `for describing topics`?

##########
File path: clients/src/main/java/org/apache/kafka/common/requests/MetadataResponse.java
##########
@@ -91,12 +91,31 @@ public int throttleTimeMs() {
     public Map<String, Errors> errors() {
         Map<String, Errors> errors = new HashMap<>();
         for (MetadataResponseTopic metadata : data.topics()) {
+            if (metadata.name() == null) {
+                throw new NullPointerException("Use errorsByTopicId() when manage topic using topic id");

Review comment:
       We should never get here through the public APIs right? We could use IllegalStateException.

##########
File path: clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
##########
@@ -350,7 +351,8 @@
     POSITION_OUT_OF_RANGE(
         99,
         "Requested position is not greater than or equal to zero, and less than the size of the snapshot.",
-        PositionOutOfRangeException::new);
+        PositionOutOfRangeException::new),
+    UNKNOWN_TOPIC_ID(100, "The topic ID dose not exist", UnknownTopicIdException::new);

Review comment:
       typo: `does`

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/TopicDescription.java
##########
@@ -79,6 +92,16 @@ public TopicDescription(String name, boolean internal, List<TopicPartitionInfo>
         this(name, internal, partitions, authorizedOperations, Uuid.ZERO_UUID);
     }
 
+    /**
+     * Create an instance with the specified parameters.
+     *
+     * @param name The topic name
+     * @param internal Whether the topic is internal to Kafka
+     * @param partitions A list of partitions where the index represents the partition id and the element contains
+     *                   leadership and replica information for that partition.
+     * @param authorizedOperations authorized operations for this topic, or null if this is not known.

Review comment:
       Looks like default is empty set rather than null?

##########
File path: clients/src/main/java/org/apache/kafka/common/requests/MetadataResponse.java
##########
@@ -91,12 +91,31 @@ public int throttleTimeMs() {
     public Map<String, Errors> errors() {
         Map<String, Errors> errors = new HashMap<>();
         for (MetadataResponseTopic metadata : data.topics()) {
+            if (metadata.name() == null) {
+                throw new NullPointerException("Use errorsByTopicId() when manage topic using topic id");
+            }
             if (metadata.errorCode() != Errors.NONE.code())
                 errors.put(metadata.name(), Errors.forCode(metadata.errorCode()));
         }
         return errors;
     }
 
+    /**
+     * Get a map of the topicIds which had metadata errors
+     * @return the map
+     */
+    public Map<Uuid, Errors> errorsByTopicId() {
+        Map<Uuid, Errors> errors = new HashMap<>();
+        for (MetadataResponseTopic metadata : data.topics()) {
+            if (metadata.topicId() == Uuid.ZERO_UUID) {
+                throw new NullPointerException("Use errors() when manage topic using topic name");

Review comment:
       As before, IllegalStateException?

##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -313,42 +313,57 @@ object TopicCommand extends Logging {
     }
 
     override def describeTopic(opts: TopicCommandOptions): Unit = {
-      val topics = getTopics(opts.topic, opts.excludeInternalTopics)
-      ensureTopicExists(topics, opts.topic, !opts.ifExists)
+      val topicId = opts.topicId.map(Uuid.fromString).filter(_ != Uuid.ZERO_UUID)
+      // if topicId is provided and not zero, will use topicId regardless of topic name

Review comment:
       we would fail if both are provided?

##########
File path: clients/src/main/java/org/apache/kafka/common/errors/UnknownTopicIdException.java
##########
@@ -0,0 +1,28 @@
+/*
+ * 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 org.apache.kafka.common.errors;
+
+public class UnknownTopicIdException extends ApiException {
+    private static final long serialVersionUID = 1L;
+    public UnknownTopicIdException() {
+        super();

Review comment:
       `super()` is implied, so we can just leave the method empty?

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
##########
@@ -1822,6 +1829,88 @@ void handleFailure(Throwable throwable) {
         return new DescribeTopicsResult(new HashMap<>(topicFutures));
     }
 
+    @Override
+    public DescribeTopicsResultWithIds describeTopicsWithIds(Collection<Uuid> topicIds, DescribeTopicsOptions options) {
+
+        final Map<Uuid, KafkaFutureImpl<TopicDescription>> topicFutures = new HashMap<>(topicIds.size());
+        final List<Uuid> topicIdsList = new ArrayList<>();
+        for (Uuid topicId : topicIds) {
+            if (topicIdIsUnrepresentable(topicId)) {
+                KafkaFutureImpl<TopicDescription> future = new KafkaFutureImpl<>();
+                future.completeExceptionally(new InvalidTopicException("The given topic id '" +
+                        topicId + "' cannot be represented in a request."));
+                topicFutures.put(topicId, future);
+            } else if (!topicFutures.containsKey(topicId)) {
+                topicFutures.put(topicId, new KafkaFutureImpl<>());
+                topicIdsList.add(topicId);
+            }
+        }
+        final long now = time.milliseconds();
+        Call call = new Call("describeTopicsWithIds", calcDeadlineMs(now, options.timeoutMs()),
+                new LeastLoadedNodeProvider()) {
+
+            @Override
+            MetadataRequest.Builder createRequest(int timeoutMs) {
+                return new MetadataRequest.Builder(new MetadataRequestData()
+                        .setTopics(convertTopicIdsToMetadataRequestTopic(topicIdsList))
+                        .setAllowAutoTopicCreation(false)
+                        .setIncludeTopicAuthorizedOperations(options.includeAuthorizedOperations()));
+            }
+
+            @Override
+            void handleResponse(AbstractResponse abstractResponse) {
+                MetadataResponse response = (MetadataResponse) abstractResponse;
+                // Handle server responses for particular topics.
+                Cluster cluster = response.cluster();
+                Map<Uuid, Errors> errors = response.errorsByTopicId();
+                for (Map.Entry<Uuid, KafkaFutureImpl<TopicDescription>> entry : topicFutures.entrySet()) {
+                    Uuid topicId = entry.getKey();
+                    KafkaFutureImpl<TopicDescription> future = entry.getValue();
+
+                    String topicName = cluster.topicName(topicId);
+                    if (topicName == null) {
+                        future.completeExceptionally(new UnknownTopicIdException("TopicId " + topicId + " not found."));
+                        continue;
+                    }
+                    Errors topicError = errors.get(topicId);
+                    if (topicError != null) {
+                        future.completeExceptionally(topicError.exception());
+                        continue;
+                    }
+
+                    boolean isInternal = cluster.internalTopics().contains(topicName);
+                    List<PartitionInfo> partitionInfos = cluster.partitionsForTopic(topicName);
+                    List<TopicPartitionInfo> partitions = new ArrayList<>(partitionInfos.size());
+                    for (PartitionInfo partitionInfo : partitionInfos) {
+                        TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(
+                                partitionInfo.partition(), leader(partitionInfo), Arrays.asList(partitionInfo.replicas()),
+                                Arrays.asList(partitionInfo.inSyncReplicas()));
+                        partitions.add(topicPartitionInfo);
+                    }
+                    partitions.sort(Comparator.comparingInt(TopicPartitionInfo::partition));
+                    TopicDescription topicDescription = new TopicDescription(topicName, isInternal, partitions,
+                            validAclOperations(response.topicAuthorizedOperations(topicName).get()), topicId);
+                    future.complete(topicDescription);

Review comment:
       Could we move the code shared between `describeTopics` and `describeTopicsWithIds` to a common private method?

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1190,8 +1192,31 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    // Check if topicId is presented firstly.
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
+    val supportedVersionTopicIds = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1) topicIds else Set.empty[Uuid]
+
+    val unSupportedVersionTopicIds = topicIds.diff(supportedVersionTopicIds)

Review comment:
       `unSupported` => `unsupported` since it is one word (below as well)

##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -313,42 +313,54 @@ object TopicCommand extends Logging {
     }
 
     override def describeTopic(opts: TopicCommandOptions): Unit = {
-      val topics = getTopics(opts.topic, opts.excludeInternalTopics)
-      ensureTopicExists(topics, opts.topic, !opts.ifExists)
+      val topicId = opts.topicId.map(Uuid.fromString).filter(_ != Uuid.ZERO_UUID)
+      val topics = if (topicId.isEmpty)
+        getTopics(opts.topic, opts.excludeInternalTopics)
+      else
+        Seq()
 
-      if (topics.nonEmpty) {
-        val allConfigs = adminClient.describeConfigs(topics.map(new ConfigResource(Type.TOPIC, _)).asJavaCollection).values()
-        val liveBrokers = adminClient.describeCluster().nodes().get().asScala.map(_.id())
-        val topicDescriptions = adminClient.describeTopics(topics.asJavaCollection).all().get().values().asScala
-        val describeOptions = new DescribeOptions(opts, liveBrokers.toSet)
-        val topicPartitions = topicDescriptions
-          .flatMap(td => td.partitions.iterator().asScala.map(p => new TopicPartition(td.name(), p.partition())))
-          .toSet.asJava
-        val reassignments = listAllReassignments(topicPartitions)
-
-        for (td <- topicDescriptions) {
-          val topicName = td.name
-          val topicId = td.topicId()
-          val config = allConfigs.get(new ConfigResource(Type.TOPIC, topicName)).get()
-          val sortedPartitions = td.partitions.asScala.sortBy(_.partition)
-
-          if (describeOptions.describeConfigs) {
-            val hasNonDefault = config.entries().asScala.exists(!_.isDefault)
-            if (!opts.reportOverriddenConfigs || hasNonDefault) {
-              val numPartitions = td.partitions().size
-              val firstPartition = td.partitions.iterator.next()
-              val reassignment = reassignments.get(new TopicPartition(td.name, firstPartition.partition))
-              val topicDesc = TopicDescription(topicName, topicId, numPartitions, getReplicationFactor(firstPartition, reassignment), config, markedForDeletion = false)
-              topicDesc.printDescription()
-            }
+      if (topicId.isEmpty)
+        ensureTopicExists(topics, opts.topic, !opts.ifExists)

Review comment:
       Since listTopics uses MetadataRequest, we just need to add topic ids from the MetadataResponse to TopicListing?




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563872442



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       Does this potentially leak the topic name when we are using topic IDs?




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-771340522


   @rajinisivaram  I run `TC_PATHS="tests/kafkatest/tests/client/client_compatibility_produce_consume_test.py" bash tests/docker/run_tests.sh` locally on the `trunk branch` version, and I also got a `ducktape.errors.TimeoutError: Consumer failed to consume messages for 60s` error. did that mean the problem is introduced by other PRs? This is weird, I havn't found out the reason for the error. 


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-764014519


   @dengziming I realized that for this, it really depends on the IBP of the controller. (That is, we need UpdateMetadata to send topic IDs to all the brokers). So maybe instead of checking IBP it would make sense to check if the MetadataCache does not have any topic IDs. What do you think?


----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-769911317


   @rajinisivaram Thank you, I think the problem comes from `EasyMock.expect(authorizer.authorize(anyObject[RequestContext], EasyMock.eq(expectedActions.asJava)))`.
   below is what I expecet:
   ```
    val expectedActions = Seq(
         new Action(AclOperation.DESCRIBE, new ResourcePattern(ResourceType.TOPIC, unauthorizedTopic, PatternType.LITERAL), 1, true, true),
         new Action(AclOperation.DESCRIBE, new ResourcePattern(ResourceType.TOPIC, authorizedTopic, PatternType.LITERAL), 1, true, true)
       )
   ```
   but maybe the order of the real params is reversed, so I removed `expectedActions` and try again.  


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r677941027



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,102 @@
+/**
+  * 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.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_3_0_IV1}
+import kafka.network.SocketServer
+import kafka.utils.TestUtils
+import kafka.zk.ZkVersion
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_3_0_IV1),

Review comment:
       I think this was discussed briefly before, but is there a reason KAFKA_3_0_IV1 was chosen? Should we just use the most recent IBP? (meaning, not even specify in the properties -- just pick up the default?)




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-875209647


   Replace deprecated methods and rebase on trunk.


-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563872705



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1247,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), false, util.Collections.emptyList()))

Review comment:
       Same here.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r562333723



##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -313,42 +313,57 @@ object TopicCommand extends Logging {
     }
 
     override def describeTopic(opts: TopicCommandOptions): Unit = {
-      val topics = getTopics(opts.topic, opts.excludeInternalTopics)
-      ensureTopicExists(topics, opts.topic, !opts.ifExists)
+      val topicId = opts.topicId.map(Uuid.fromString).filter(_ != Uuid.ZERO_UUID)
+      // if topicId is provided and not zero, will use topicId regardless of topic name

Review comment:
       that's what I thought at the beginning, now I think it's better to use topicId and print a warning message if both are provided.




----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-770860477


   @dengziming Yes, if you are able to run those two tests locally, that will be good. The failures looked similar with consumer failing to consume, so I guess may be only one issue to figure out (it is not 100% clear if the issue is with this PR).


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r665479977



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,103 @@
+/**
+  * 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.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_3_0_IV1}
+import kafka.network.SocketServer
+import kafka.utils.TestUtils
+import kafka.zk.ZkVersion
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_3_0_IV1),
+      createConfig(2, KAFKA_3_0_IV1)
+    )
+  }
+
+  @Test
+  def testUnknownTopicId(): Unit = {
+    val topic = "topic"
+
+    // Kill controller and restart until broker 2 become controller
+    ensureControllerIn(Seq(1, 2))
+    createTopic(topic, Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 12.toShort), controllerSocketServer)
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+
+    // We could still get topic metadata by topicId
+   val topicMetadata = sendMetadataRequest(new MetadataRequest(requestData(null, topicId), 12.toShort), controllerSocketServer)
+      .topicMetadata.iterator().next()
+    assertEquals(topicId, topicMetadata.topicId())
+    assertEquals(topic, topicMetadata.topic())
+
+    // Make the broker whose version=KAFKA_3_0_IV0 controller

Review comment:
       I'm not sure this comment is correct since we don't use this version. 
   Just to confirm my understanding, what is this test showing? First we can get description when controller is high enough IBP (2_8_IV1+) and then we can't when controller is lower than that?




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r556178594



##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -742,10 +760,16 @@ object TopicCommand extends Logging {
       if (has(bootstrapServerOpt) == has(zkConnectOpt))
         throw new IllegalArgumentException("Only one of --bootstrap-server or --zookeeper must be specified")
 
+      if (has(topicIdOpt) && has(zkConnectOpt)) {
+        throw new IllegalArgumentException("--topic-id can used only with --bootstrap-server")
+      }
+
       if (!has(bootstrapServerOpt))
         CommandLineUtils.checkRequiredArgs(parser, options, zkConnectOpt)
-      if(has(describeOpt) && has(ifExistsOpt))
-        CommandLineUtils.checkRequiredArgs(parser, options, topicOpt)

Review comment:
       Yes, when we use `--describe`, `--topic` is not mandatory. I add a `if(has(topicOpt) == has(topicIdOpt))` to ensure only one of `--topic` and `--topic-id` is used. 




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-771340522


   @rajinisivaram  I run `TC_PATHS="tests/kafkatest/tests/client/client_compatibility_produce_consume_test.py" bash tests/docker/run_tests.sh` locally on the `trunk branch` version, and I also got a `ducktape.errors.TimeoutError: Consumer failed to consume messages for 60s` error. did that mean the problem is introduced by other PRs? This is weird, I havn't found out the reason for the error. 


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563903351



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       (and if we give ID when using name, we acknowledge it exists)




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming edited a comment on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming edited a comment on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-769911317


   @rajinisivaram Thank you, I think the problem comes from `EasyMock.expect(authorizer.authorize(anyObject[RequestContext], EasyMock.eq(expectedActions.asJava)))`.
   below is what I expecet:
   ```
    val expectedActions = Seq(
         new Action(AclOperation.DESCRIBE, new ResourcePattern(ResourceType.TOPIC, unauthorizedTopic, PatternType.LITERAL), 1, true, true),
         new Action(AclOperation.DESCRIBE, new ResourcePattern(ResourceType.TOPIC, authorizedTopic, PatternType.LITERAL), 1, true, true)
       )
   ```
   but maybe the order of the real params is reversed, so make some change.


----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-771541128






----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r555730755



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/TopicDescription.java
##########
@@ -62,25 +62,25 @@ public int hashCode() {
      *                   leadership and replica information for that partition.
      */
     public TopicDescription(String name, boolean internal, List<TopicPartitionInfo> partitions) {
-        this(name, internal, partitions, Collections.emptySet());
+        this(name, Uuid.ZERO_UUID, internal, partitions);
+    }
+
+    public TopicDescription(String name, Uuid topicId, boolean internal, List<TopicPartitionInfo> partitions) {
+        this(name, topicId, internal, partitions, Collections.emptySet());
     }
 
     /**
      * Create an instance with the specified parameters.
      *
      * @param name The topic name
+     * @param topicId the topic id
      * @param internal Whether the topic is internal to Kafka
      * @param partitions A list of partitions where the index represents the partition id and the element contains
      *                   leadership and replica information for that partition.
      * @param authorizedOperations authorized operations for this topic, or null if this is not known.
      */
-    public TopicDescription(String name, boolean internal, List<TopicPartitionInfo> partitions,
+    public TopicDescription(String name, Uuid topicId, boolean internal, List<TopicPartitionInfo> partitions,

Review comment:
       We seemed to have removed a constructor?

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
##########
@@ -1816,7 +1823,103 @@ void handleFailure(Throwable throwable) {
         if (!topicNamesList.isEmpty()) {
             runnable.call(call, now);
         }
-        return new DescribeTopicsResult(new HashMap<>(topicFutures));
+        return new DescribeTopicsResult<>(new HashMap<>(topicFutures));
+    }
+
+    @Override
+    public DescribeTopicsResult<Uuid> describeTopicsWithIds(Collection<Uuid> topicIds, DescribeTopicsOptions options) {
+
+        final Map<Uuid, KafkaFutureImpl<TopicDescription>> topicFutures = new HashMap<>(topicIds.size());
+        final List<Uuid> topicIdsList = new ArrayList<>();
+        for (Uuid topicId : topicIds) {
+            if (topicIdIsUnrepresentable(topicId)) {
+                KafkaFutureImpl<TopicDescription> future = new KafkaFutureImpl<>();
+                future.completeExceptionally(new InvalidTopicException("The given topic id '" +
+                        topicId + "' cannot be represented in a request."));
+                topicFutures.put(topicId, future);
+            } else if (!topicFutures.containsKey(topicId)) {
+                topicFutures.put(topicId, new KafkaFutureImpl<>());
+                topicIdsList.add(topicId);
+            }
+        }
+        final long now = time.milliseconds();
+        Call call = new Call("describeTopicsWithIds", calcDeadlineMs(now, options.timeoutMs()),
+                new LeastLoadedNodeProvider()) {
+
+            private boolean supportsDisablingTopicCreation = true;
+
+            @Override
+            MetadataRequest.Builder createRequest(int timeoutMs) {
+                if (supportsDisablingTopicCreation)
+                    return new MetadataRequest.Builder(new MetadataRequestData()
+                            .setTopics(convertTopicIdsToMetadataRequestTopic(topicIdsList))
+                            .setAllowAutoTopicCreation(false)
+                            .setIncludeTopicAuthorizedOperations(options.includeAuthorizedOperations()));
+                else
+                    return MetadataRequest.Builder.allTopics();
+            }
+
+            @Override
+            void handleResponse(AbstractResponse abstractResponse) {
+                MetadataResponse response = (MetadataResponse) abstractResponse;
+                // Handle server responses for particular topics.
+                Cluster cluster = response.cluster();
+                Map<String, Errors> errors = response.errors();
+                for (Map.Entry<Uuid, KafkaFutureImpl<TopicDescription>> entry : topicFutures.entrySet()) {
+                    Uuid topicId = entry.getKey();
+                    KafkaFutureImpl<TopicDescription> future = entry.getValue();
+
+                    String topicName = cluster.topicName(topicId);
+                    if (topicName == null) {
+                        future.completeExceptionally(new UnknownTopicIdException("TopicId " + topicId + " not found."));
+                        continue;
+                    }
+                    Errors topicError = errors.get(topicName);
+                    if (topicError != null) {
+                        future.completeExceptionally(topicError.exception());
+                        continue;
+                    }
+
+                    boolean isInternal = cluster.internalTopics().contains(topicName);
+                    List<PartitionInfo> partitionInfos = cluster.partitionsForTopic(topicName);
+                    List<TopicPartitionInfo> partitions = new ArrayList<>(partitionInfos.size());
+                    for (PartitionInfo partitionInfo : partitionInfos) {
+                        TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(
+                                partitionInfo.partition(), leader(partitionInfo), Arrays.asList(partitionInfo.replicas()),
+                                Arrays.asList(partitionInfo.inSyncReplicas()));
+                        partitions.add(topicPartitionInfo);
+                    }
+                    partitions.sort(Comparator.comparingInt(TopicPartitionInfo::partition));
+                    TopicDescription topicDescription = new TopicDescription(topicName, topicId, isInternal, partitions,
+                            validAclOperations(response.topicAuthorizedOperations(topicName).get()));
+                    future.complete(topicDescription);
+                }
+            }
+
+            private Node leader(PartitionInfo partitionInfo) {
+                if (partitionInfo.leader() == null || partitionInfo.leader().id() == Node.noNode().id())
+                    return null;
+                return partitionInfo.leader();
+            }
+
+            @Override
+            boolean handleUnsupportedVersionException(UnsupportedVersionException exception) {
+                if (supportsDisablingTopicCreation) {
+                    supportsDisablingTopicCreation = false;

Review comment:
       Couldn't unsupported version mean that topic ids are not supported (rather than `disablingTopicCreation`)? In any case, you can't create topics with topic ids right?

##########
File path: clients/src/main/java/org/apache/kafka/common/requests/MetadataResponse.java
##########
@@ -91,7 +91,7 @@ public int throttleTimeMs() {
     public Map<String, Errors> errors() {
         Map<String, Errors> errors = new HashMap<>();
         for (MetadataResponseTopic metadata : data.topics()) {
-            if (metadata.errorCode() != Errors.NONE.code())
+            if (metadata.errorCode() != Errors.NONE.code() && metadata.name() != null)

Review comment:
       What happens if `name` is null - won't we quietly ignore? Would it be better to throw an exception since we don't want anyone using this with topic ids?

##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -313,42 +313,54 @@ object TopicCommand extends Logging {
     }
 
     override def describeTopic(opts: TopicCommandOptions): Unit = {
-      val topics = getTopics(opts.topic, opts.excludeInternalTopics)
-      ensureTopicExists(topics, opts.topic, !opts.ifExists)
+      val topicId = opts.topicId.map(Uuid.fromString).filter(_ != Uuid.ZERO_UUID)
+      val topics = if (topicId.isEmpty)
+        getTopics(opts.topic, opts.excludeInternalTopics)
+      else
+        Seq()
 
-      if (topics.nonEmpty) {
-        val allConfigs = adminClient.describeConfigs(topics.map(new ConfigResource(Type.TOPIC, _)).asJavaCollection).values()
-        val liveBrokers = adminClient.describeCluster().nodes().get().asScala.map(_.id())
-        val topicDescriptions = adminClient.describeTopics(topics.asJavaCollection).all().get().values().asScala
-        val describeOptions = new DescribeOptions(opts, liveBrokers.toSet)
-        val topicPartitions = topicDescriptions
-          .flatMap(td => td.partitions.iterator().asScala.map(p => new TopicPartition(td.name(), p.partition())))
-          .toSet.asJava
-        val reassignments = listAllReassignments(topicPartitions)
-
-        for (td <- topicDescriptions) {
-          val topicName = td.name
-          val topicId = td.topicId()
-          val config = allConfigs.get(new ConfigResource(Type.TOPIC, topicName)).get()
-          val sortedPartitions = td.partitions.asScala.sortBy(_.partition)
-
-          if (describeOptions.describeConfigs) {
-            val hasNonDefault = config.entries().asScala.exists(!_.isDefault)
-            if (!opts.reportOverriddenConfigs || hasNonDefault) {
-              val numPartitions = td.partitions().size
-              val firstPartition = td.partitions.iterator.next()
-              val reassignment = reassignments.get(new TopicPartition(td.name, firstPartition.partition))
-              val topicDesc = TopicDescription(topicName, topicId, numPartitions, getReplicationFactor(firstPartition, reassignment), config, markedForDeletion = false)
-              topicDesc.printDescription()
-            }
+      if (topicId.isEmpty)
+        ensureTopicExists(topics, opts.topic, !opts.ifExists)

Review comment:
       `topics` may also be empty?

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -31,29 +31,29 @@
  * The API of this class is evolving, see {@link Admin} for details.
  */
 @InterfaceStability.Evolving
-public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+public class DescribeTopicsResult<T> {

Review comment:
       We need to keep the Admin API backwards compatible. An application that was written using the 2.7.0 should not break if it is compiled with a 2.8.0 clients jar. You can always add an internal class with shared code to avoid duplication, but the public API itself needs to remain compatible.

##########
File path: clients/src/test/java/org/apache/kafka/clients/admin/MockAdminClient.java
##########
@@ -206,6 +209,8 @@ synchronized public void addTopic(boolean internal,
                 logDirs.add(brokerLogDirs.get(partition.leader().id()).get(0));
             }
         }
+        Uuid topicId = Uuid.randomUuid();
+        topicIds.put(name, topicId);

Review comment:
       Do we want the option to test with and without topic ids?

##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -742,10 +760,16 @@ object TopicCommand extends Logging {
       if (has(bootstrapServerOpt) == has(zkConnectOpt))
         throw new IllegalArgumentException("Only one of --bootstrap-server or --zookeeper must be specified")
 
+      if (has(topicIdOpt) && has(zkConnectOpt)) {
+        throw new IllegalArgumentException("--topic-id can used only with --bootstrap-server")
+      }
+
       if (!has(bootstrapServerOpt))
         CommandLineUtils.checkRequiredArgs(parser, options, zkConnectOpt)
-      if(has(describeOpt) && has(ifExistsOpt))
-        CommandLineUtils.checkRequiredArgs(parser, options, topicOpt)

Review comment:
       We have removed this check?




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563969840



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1247,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), false, util.Collections.emptyList()))

Review comment:
       We should check some of the other error responses to make sure we use name/id appropriately




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-766972011


   I added a few comments. Mostly just questions for clarification.


----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram merged pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram merged pull request #9769:
URL: https://github.com/apache/kafka/pull/9769


   


-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r555923055



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
##########
@@ -1816,7 +1823,103 @@ void handleFailure(Throwable throwable) {
         if (!topicNamesList.isEmpty()) {
             runnable.call(call, now);
         }
-        return new DescribeTopicsResult(new HashMap<>(topicFutures));
+        return new DescribeTopicsResult<>(new HashMap<>(topicFutures));
+    }
+
+    @Override
+    public DescribeTopicsResult<Uuid> describeTopicsWithIds(Collection<Uuid> topicIds, DescribeTopicsOptions options) {
+
+        final Map<Uuid, KafkaFutureImpl<TopicDescription>> topicFutures = new HashMap<>(topicIds.size());
+        final List<Uuid> topicIdsList = new ArrayList<>();
+        for (Uuid topicId : topicIds) {
+            if (topicIdIsUnrepresentable(topicId)) {
+                KafkaFutureImpl<TopicDescription> future = new KafkaFutureImpl<>();
+                future.completeExceptionally(new InvalidTopicException("The given topic id '" +
+                        topicId + "' cannot be represented in a request."));
+                topicFutures.put(topicId, future);
+            } else if (!topicFutures.containsKey(topicId)) {
+                topicFutures.put(topicId, new KafkaFutureImpl<>());
+                topicIdsList.add(topicId);
+            }
+        }
+        final long now = time.milliseconds();
+        Call call = new Call("describeTopicsWithIds", calcDeadlineMs(now, options.timeoutMs()),
+                new LeastLoadedNodeProvider()) {
+
+            private boolean supportsDisablingTopicCreation = true;
+
+            @Override
+            MetadataRequest.Builder createRequest(int timeoutMs) {
+                if (supportsDisablingTopicCreation)
+                    return new MetadataRequest.Builder(new MetadataRequestData()
+                            .setTopics(convertTopicIdsToMetadataRequestTopic(topicIdsList))
+                            .setAllowAutoTopicCreation(false)
+                            .setIncludeTopicAuthorizedOperations(options.includeAuthorizedOperations()));
+                else
+                    return MetadataRequest.Builder.allTopics();
+            }
+
+            @Override
+            void handleResponse(AbstractResponse abstractResponse) {
+                MetadataResponse response = (MetadataResponse) abstractResponse;
+                // Handle server responses for particular topics.
+                Cluster cluster = response.cluster();
+                Map<String, Errors> errors = response.errors();
+                for (Map.Entry<Uuid, KafkaFutureImpl<TopicDescription>> entry : topicFutures.entrySet()) {
+                    Uuid topicId = entry.getKey();
+                    KafkaFutureImpl<TopicDescription> future = entry.getValue();
+
+                    String topicName = cluster.topicName(topicId);
+                    if (topicName == null) {
+                        future.completeExceptionally(new UnknownTopicIdException("TopicId " + topicId + " not found."));
+                        continue;
+                    }
+                    Errors topicError = errors.get(topicName);
+                    if (topicError != null) {
+                        future.completeExceptionally(topicError.exception());
+                        continue;
+                    }
+
+                    boolean isInternal = cluster.internalTopics().contains(topicName);
+                    List<PartitionInfo> partitionInfos = cluster.partitionsForTopic(topicName);
+                    List<TopicPartitionInfo> partitions = new ArrayList<>(partitionInfos.size());
+                    for (PartitionInfo partitionInfo : partitionInfos) {
+                        TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(
+                                partitionInfo.partition(), leader(partitionInfo), Arrays.asList(partitionInfo.replicas()),
+                                Arrays.asList(partitionInfo.inSyncReplicas()));
+                        partitions.add(topicPartitionInfo);
+                    }
+                    partitions.sort(Comparator.comparingInt(TopicPartitionInfo::partition));
+                    TopicDescription topicDescription = new TopicDescription(topicName, topicId, isInternal, partitions,
+                            validAclOperations(response.topicAuthorizedOperations(topicName).get()));
+                    future.complete(topicDescription);
+                }
+            }
+
+            private Node leader(PartitionInfo partitionInfo) {
+                if (partitionInfo.leader() == null || partitionInfo.leader().id() == Node.noNode().id())
+                    return null;
+                return partitionInfo.leader();
+            }
+
+            @Override
+            boolean handleUnsupportedVersionException(UnsupportedVersionException exception) {
+                if (supportsDisablingTopicCreation) {
+                    supportsDisablingTopicCreation = false;

Review comment:
       For the second question, yes. Topics can not be created with metadata requests using topic IDs.




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-865491775


   Hi @dengziming thanks for the update. There are a few more minor changes to the KIP.
   One is that after some discussion with people more familiar with clients, it makes sense to remove the UNSUPPORTED_VERSION error and only return UNKNOWN_TOPIC_ID when the topic ID is not found on the broker. (See: https://issues.apache.org/jira/browse/KAFKA-12976)


-- 
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r564222778



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,125 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import kafka.zk.ZkVersion
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_2_8_IV1),
+      createConfig(2, KAFKA_2_8_IV1)
+    )
+  }
+
+  @Test
+  def testTopicIdUnsupported(): Unit = {
+
+    val topic = "topic"
+
+    // Ensure controller version = KAFKA_2_8_IV1, and then create a topic
+    ensureControllerIn(Seq(1, 2))
+    createTopic(topic,  Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    // We can get topicId from the controller
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), controllerSocketServer)
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+    assertNotEquals(Uuid.ZERO_UUID, topicId)
+    assertNotNull(topicId)
+
+    // Send request to a broker whose version=KAFKA_2_8_IV0
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(0))
+    assertEquals(Errors.UNSUPPORTED_VERSION, resp2.topicMetadata.iterator().next().error())
+  }
+
+  @Test
+  def testUnknownTopicId(): Unit = {
+
+    val topic = "topic"
+
+    // Kill controller and restart until broker 2 become controller
+    ensureControllerIn(Seq(1, 2))
+    createTopic(topic, Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), controllerSocketServer)
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+
+    // We could still get topic metadata by topicId
+    val topicMetadata = sendMetadataRequest(new MetadataRequest(requestData(null, topicId), 10.toShort), controllerSocketServer)
+      .topicMetadata.iterator().next()
+    assertEquals(topicId, topicMetadata.topicId())
+    assertEquals(topic, topicMetadata.topic())
+
+    // Make the broker whose version=KAFKA_2_8_IV0 controller
+    ensureControllerIn(Seq(0))
+
+    // Restart the broker whose version=KAFKA_2_8_IV1, and the controller will send metadata request to it
+    killBroker(1)
+    restartDeadBrokers()
+
+    // Send request to a broker whose version=KAFKA_2_8_IV1 and restarted just now
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(1))
+    assertEquals(Errors.UNKNOWN_TOPIC_ID, resp2.topicMetadata.iterator().next().error())

Review comment:
       Yes, both ERROR is ok here.




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-772830472


   @dengziming I don't know if you saw the mailing list discussion on this KIP, but the summary is that I talked to Ismael offline and we thought it would be good to hold off on the Admin Client APIs until after the 2.8 release is cut. I mentioned in that thread about splitting this PR into two, but on further thought, I think it makes sense to wait until after 2.8 is cut.


----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r555810587



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1238,8 +1239,21 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)

Review comment:
       OK, I will add these check after 9814 merged.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-764402380


   @rajinisivaram I rebased the code and added a test in `PlaintextAdminIntegrationTest`, PTAL.


----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r556180111



##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -313,42 +313,54 @@ object TopicCommand extends Logging {
     }
 
     override def describeTopic(opts: TopicCommandOptions): Unit = {
-      val topics = getTopics(opts.topic, opts.excludeInternalTopics)
-      ensureTopicExists(topics, opts.topic, !opts.ifExists)
+      val topicId = opts.topicId.map(Uuid.fromString).filter(_ != Uuid.ZERO_UUID)
+      val topics = if (topicId.isEmpty)
+        getTopics(opts.topic, opts.excludeInternalTopics)
+      else
+        Seq()
 
-      if (topics.nonEmpty) {
-        val allConfigs = adminClient.describeConfigs(topics.map(new ConfigResource(Type.TOPIC, _)).asJavaCollection).values()
-        val liveBrokers = adminClient.describeCluster().nodes().get().asScala.map(_.id())
-        val topicDescriptions = adminClient.describeTopics(topics.asJavaCollection).all().get().values().asScala
-        val describeOptions = new DescribeOptions(opts, liveBrokers.toSet)
-        val topicPartitions = topicDescriptions
-          .flatMap(td => td.partitions.iterator().asScala.map(p => new TopicPartition(td.name(), p.partition())))
-          .toSet.asJava
-        val reassignments = listAllReassignments(topicPartitions)
-
-        for (td <- topicDescriptions) {
-          val topicName = td.name
-          val topicId = td.topicId()
-          val config = allConfigs.get(new ConfigResource(Type.TOPIC, topicName)).get()
-          val sortedPartitions = td.partitions.asScala.sortBy(_.partition)
-
-          if (describeOptions.describeConfigs) {
-            val hasNonDefault = config.entries().asScala.exists(!_.isDefault)
-            if (!opts.reportOverriddenConfigs || hasNonDefault) {
-              val numPartitions = td.partitions().size
-              val firstPartition = td.partitions.iterator.next()
-              val reassignment = reassignments.get(new TopicPartition(td.name, firstPartition.partition))
-              val topicDesc = TopicDescription(topicName, topicId, numPartitions, getReplicationFactor(firstPartition, reassignment), config, markedForDeletion = false)
-              topicDesc.printDescription()
-            }
+      if (topicId.isEmpty)
+        ensureTopicExists(topics, opts.topic, !opts.ifExists)

Review comment:
       Here, if topic is provided, we ensure topic exists since the given topic maybe a regular expr. should we also check the topicId exists? then we should add a listTopicId method `listTopicIds` in the AdminClient




----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563620794



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,117 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_2_8_IV1)

Review comment:
       Don't we need the config for the third broker?

##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,117 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_2_8_IV1)
+    )
+  }
+
+  @Test
+  def testTopicIdUnsupported(): Unit = {
+
+    val topic = "topic"
+
+    // Ensure controller version = KAFKA_2_8_IV1, and then create a topic
+    ensureControllerIn(Seq(1))
+    createTopic(topic,  Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    // We can get topicId from the controller
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), brokerSocketServer(1))
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+    assertNotEquals(Uuid.ZERO_UUID, topicId)
+    assertNotNull(topicId)
+
+    // Send request to a broker whose version=KAFKA_2_8_IV0
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(0))
+    assertEquals(Errors.UNSUPPORTED_VERSION, resp2.topicMetadata.iterator().next().error())
+  }
+
+  @Test
+  def testUnknownTopicId(): Unit = {
+
+    val topic = "topic"
+
+    // Kill controller and restart until broker 2 become controller
+    ensureControllerIn(Seq(1))
+    createTopic(topic, Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), brokerSocketServer(1))
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+
+    // We could still get topic metadata by topicId
+    val topicMetadata = sendMetadataRequest(new MetadataRequest(requestData(null, topicId), 10.toShort), brokerSocketServer(1))
+      .topicMetadata.iterator().next()
+    assertEquals(topicId, topicMetadata.topicId())
+    assertEquals(topic, topicMetadata.topic())
+
+    // Make the broker whose version=KAFKA_2_8_IV0 controller
+    ensureControllerIn(Seq(0))
+
+    // Restart the broker whose version=KAFKA_2_8_IV1, and the controller will send metadata request to it
+    killBroker(1)
+    restartDeadBrokers()
+
+    // Send request to a broker whose version=KAFKA_2_8_IV1
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(1))
+    assertEquals(Errors.UNKNOWN_TOPIC_ID, resp2.topicMetadata.iterator().next().error())
+  }
+
+  private def ensureControllerIn(brokerIds: Seq[Int]): Unit = {
+    while (!brokerIds.contains(controllerSocketServer.config.brokerId)) {
+      killBroker(controllerSocketServer.config.brokerId)

Review comment:
       Instead of restarting brokers, we could delete the controller node in ZK to force controller election. It doesn't guarantee that the expected broker id becomes the next controller, but it may still get there faster than broker restarts




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563872705



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1247,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), false, util.Collections.emptyList()))

Review comment:
       Does this potentially leak the topic name when we are using topic IDs? And potentially acknowledge a topic exists if we give a valid id?




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r556177548



##########
File path: clients/src/main/java/org/apache/kafka/common/requests/MetadataResponse.java
##########
@@ -91,7 +91,7 @@ public int throttleTimeMs() {
     public Map<String, Errors> errors() {
         Map<String, Errors> errors = new HashMap<>();
         for (MetadataResponseTopic metadata : data.topics()) {
-            if (metadata.errorCode() != Errors.NONE.code())
+            if (metadata.errorCode() != Errors.NONE.code() && metadata.name() != null)

Review comment:
       Firstly I want to leave those check to callers, now I think it's better to throw an exception, So I add another method errorsByTopicId.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-765133359


   Hello, @rajinisivaram , I resolved the comments/questions and fixed the NullPointerExceptions, call for a third review. 
   1. Add topicId to`TopicListing ` and add `TopicCommand.getTopicIds`
   2. move the code shared between describeTopics and describeTopicsWithIds to a common private method `getTopicDescriptionFromCluster`.


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r664075804



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -32,28 +34,87 @@
  */
 @InterfaceStability.Evolving
 public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+    private final Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures;
+    private final Map<String, KafkaFuture<TopicDescription>> nameFutures;
 
-    protected DescribeTopicsResult(Map<String, KafkaFuture<TopicDescription>> futures) {
-        this.futures = futures;
+    protected DescribeTopicsResult(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures, Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        if (topicIdFutures != null && nameFutures != null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be specified.");
+        if (topicIdFutures == null && nameFutures == null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be null.");
+        this.topicIdFutures = topicIdFutures;
+        this.nameFutures = nameFutures;
+    }
+
+    static DescribeTopicsResult ofTopicIds(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures) {
+        return new DescribeTopicsResult(topicIdFutures, null);
+    }
+
+    static DescribeTopicsResult ofTopicNames(Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        return new DescribeTopicsResult(null, nameFutures);
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicIdCollection
+     *
+     * @return a map from topic IDs to futures which can be used to check the status of
+     *         individual topics if the request used topic IDs, otherwise return null.
+     */
+    public Map<Uuid, KafkaFuture<TopicDescription>> topicIdValues() {
+        return topicIdFutures;
     }
 
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicNameCollection
+     *
+     * @return a map from topic names to futures which can be used to check the status of
+     *         individual topics if the request used topic names, otherwise return null.
+     */
+    public Map<String, KafkaFuture<TopicDescription>> topicNameValues() {
+        return nameFutures;
+    }
+
+
     /**
      * Return a map from topic names to futures which can be used to check the status of
      * individual topics.
      */
+    @Deprecated
     public Map<String, KafkaFuture<TopicDescription>> values() {
-        return futures;
+        return nameFutures;
     }
 
     /**
      * Return a future which succeeds only if all the topic descriptions succeed.
      */
     public KafkaFuture<Map<String, TopicDescription>> all() {
-        return KafkaFuture.allOf(futures.values().toArray(new KafkaFuture[0])).
+        return all(nameFutures);

Review comment:
       We should deprecate this one too I believe.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] rajinisivaram commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r562511974



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1190,8 +1192,31 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    // Check if topicId is presented firstly.
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
+    val supportedVersionTopicIds = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1) topicIds else Set.empty[Uuid]

Review comment:
       Had a chat offline with Justine. Since `KafkaConfig.usesTopicId` is used only to decide whether to generate topic ids, 2_8_IV0 makes sense for that, and the check for KAFKA_2_8_IV1 here is the right one. Justine also mentioned:
   
   > if we are in the process of bumping to 2_8_IV1, we could have a scenario where the controller is not yet bumped (and not sending topic IDs) but the broker serving the metadata is. In that case I think we would just get unknown topic ID errors and maybe that is ok. If the reverse is occurring, we could also have unsupported version exception when there are actually IDs.
   
   
   Can we add tests for these two cases?




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-764219186






----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r664075804



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -32,28 +34,87 @@
  */
 @InterfaceStability.Evolving
 public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+    private final Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures;
+    private final Map<String, KafkaFuture<TopicDescription>> nameFutures;
 
-    protected DescribeTopicsResult(Map<String, KafkaFuture<TopicDescription>> futures) {
-        this.futures = futures;
+    protected DescribeTopicsResult(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures, Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        if (topicIdFutures != null && nameFutures != null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be specified.");
+        if (topicIdFutures == null && nameFutures == null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be null.");
+        this.topicIdFutures = topicIdFutures;
+        this.nameFutures = nameFutures;
+    }
+
+    static DescribeTopicsResult ofTopicIds(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures) {
+        return new DescribeTopicsResult(topicIdFutures, null);
+    }
+
+    static DescribeTopicsResult ofTopicNames(Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        return new DescribeTopicsResult(null, nameFutures);
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicIdCollection
+     *
+     * @return a map from topic IDs to futures which can be used to check the status of
+     *         individual topics if the request used topic IDs, otherwise return null.
+     */
+    public Map<Uuid, KafkaFuture<TopicDescription>> topicIdValues() {
+        return topicIdFutures;
     }
 
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicNameCollection
+     *
+     * @return a map from topic names to futures which can be used to check the status of
+     *         individual topics if the request used topic names, otherwise return null.
+     */
+    public Map<String, KafkaFuture<TopicDescription>> topicNameValues() {
+        return nameFutures;
+    }
+
+
     /**
      * Return a map from topic names to futures which can be used to check the status of
      * individual topics.
      */
+    @Deprecated
     public Map<String, KafkaFuture<TopicDescription>> values() {
-        return futures;
+        return nameFutures;
     }
 
     /**
      * Return a future which succeeds only if all the topic descriptions succeed.
      */
     public KafkaFuture<Map<String, TopicDescription>> all() {
-        return KafkaFuture.allOf(futures.values().toArray(new KafkaFuture[0])).
+        return all(nameFutures);

Review comment:
       We should deprecate this one too I believe.

##########
File path: clients/src/main/java/org/apache/kafka/common/requests/MetadataRequest.java
##########
@@ -65,6 +65,20 @@ public Builder(List<String> topics, boolean allowAutoTopicCreation) {
             this(topics, allowAutoTopicCreation, ApiKeys.METADATA.oldestVersion(),  ApiKeys.METADATA.latestVersion());
         }
 
+        public Builder(List<Uuid> topicIds) {
+            super(ApiKeys.METADATA, ApiKeys.METADATA.oldestVersion(), ApiKeys.METADATA.latestVersion());
+            MetadataRequestData data = new MetadataRequestData();
+            if (topicIds == null)
+                data.setTopics(null);
+            else {
+                topicIds.forEach(topicId -> data.topics().add(new MetadataRequestTopic().setTopicId(topicId).setName("")));

Review comment:
       Is there a reason this is setting the name to empty and not null? (or no name set at all?)

##########
File path: clients/src/main/resources/common/message/MetadataResponse.json
##########
@@ -65,7 +66,7 @@
       "about": "Each topic in the response.", "fields": [
       { "name": "ErrorCode", "type": "int16", "versions": "0+",
         "about": "The topic error, or 0 if there was no error." },
-      { "name": "Name", "type": "string", "versions": "0+", "mapKey": true, "entityType": "topicName",
+      { "name": "Name", "type": "string", "versions": "0+", "mapKey": true, "entityType": "topicName", "nullableVersions": "10+",

Review comment:
       can we set a previous version to be nullable? Or does this need to be 12+

##########
File path: core/src/main/scala/kafka/api/ApiVersion.scala
##########
@@ -116,7 +116,9 @@ object ApiVersion {
     // Introduce AllocateProducerIds (KIP-730)
     KAFKA_3_0_IV0,
     // Introduce ListOffsets V7 which supports listing offsets by max timestamp (KIP-734)
-    KAFKA_3_0_IV1
+    KAFKA_3_0_IV1,
+    // Introduced topic IDs to MetadataRequest

Review comment:
       Why are we bumping IBP? Metadata is not an inter-broker protocol, so I think bumping the metadata protocol suffices.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563861257



##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -313,42 +313,57 @@ object TopicCommand extends Logging {
     }
 
     override def describeTopic(opts: TopicCommandOptions): Unit = {
-      val topics = getTopics(opts.topic, opts.excludeInternalTopics)
-      ensureTopicExists(topics, opts.topic, !opts.ifExists)
+      val topicId = opts.topicId.map(Uuid.fromString).filter(_ != Uuid.ZERO_UUID)
+      // if topicId is provided and not zero, will use topicId regardless of topic name

Review comment:
       I don't have an issue with this, but just curious why this was chosen over failing.

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1190,8 +1192,31 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    // Check if topicId is presented firstly.
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
+    val supportedVersionTopicIds = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1) topicIds else Set.empty[Uuid]
+
+    val unsupportedVersionTopicIds = topicIds.diff(supportedVersionTopicIds)

Review comment:
       I'm curious if this diff is needed. It seems that the above check will result in all topicIds being left out or all of them being included.

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       Does this potentially leak the topic name when we are using topic IDs?

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1247,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), false, util.Collections.emptyList()))

Review comment:
       Same here.

##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,125 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import kafka.zk.ZkVersion
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {

Review comment:
       This test is super cool and will be very useful when testing other request types like fetch. 

##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,125 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import kafka.zk.ZkVersion
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_2_8_IV1),
+      createConfig(2, KAFKA_2_8_IV1)
+    )
+  }
+
+  @Test
+  def testTopicIdUnsupported(): Unit = {
+
+    val topic = "topic"
+
+    // Ensure controller version = KAFKA_2_8_IV1, and then create a topic
+    ensureControllerIn(Seq(1, 2))
+    createTopic(topic,  Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    // We can get topicId from the controller
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), controllerSocketServer)
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+    assertNotEquals(Uuid.ZERO_UUID, topicId)
+    assertNotNull(topicId)
+
+    // Send request to a broker whose version=KAFKA_2_8_IV0
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(0))
+    assertEquals(Errors.UNSUPPORTED_VERSION, resp2.topicMetadata.iterator().next().error())
+  }
+
+  @Test
+  def testUnknownTopicId(): Unit = {
+
+    val topic = "topic"
+
+    // Kill controller and restart until broker 2 become controller
+    ensureControllerIn(Seq(1, 2))
+    createTopic(topic, Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), controllerSocketServer)
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+
+    // We could still get topic metadata by topicId
+    val topicMetadata = sendMetadataRequest(new MetadataRequest(requestData(null, topicId), 10.toShort), controllerSocketServer)
+      .topicMetadata.iterator().next()
+    assertEquals(topicId, topicMetadata.topicId())
+    assertEquals(topic, topicMetadata.topic())
+
+    // Make the broker whose version=KAFKA_2_8_IV0 controller
+    ensureControllerIn(Seq(0))
+
+    // Restart the broker whose version=KAFKA_2_8_IV1, and the controller will send metadata request to it
+    killBroker(1)
+    restartDeadBrokers()
+
+    // Send request to a broker whose version=KAFKA_2_8_IV1 and restarted just now
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(1))
+    assertEquals(Errors.UNKNOWN_TOPIC_ID, resp2.topicMetadata.iterator().next().error())

Review comment:
       This scenario is a bit of a corner case and maybe not a huge deal either way, but does it make more sense to respond with UNKNOWN_TOPIC_ID or UNSUPPORTED_VERSION here? Maybe either is fine since we can expect UNKNOWN_TOPIC_ID or UNSUPPORTED_VERSION during an upgrade like this anyway.

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       (and if we give ID when using name, we acknowledge it exists)

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       Does this potentially leak the topic name when we are using topic IDs?

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       (and if we give ID when using name, we acknowledge it exists)

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1247,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), false, util.Collections.emptyList()))

Review comment:
       Does this potentially leak the topic name when we are using topic IDs? And potentially acknowledge a topic exists if we give a valid id?

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       I think we only care about authorizedForCreate when using topic names. but just want to make sure we don't give a name/id away

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       I think this usage is fine since we will only get here if use the topic name version of the request and the topic does not exist.

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1247,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), false, util.Collections.emptyList()))

Review comment:
       Does this potentially acknowledge a topic exists if we give a valid id?

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1247,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), false, util.Collections.emptyList()))

Review comment:
       We should check some of the other error responses to make sure we use name/id appropriately




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r566227520



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1213,8 +1238,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
-
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), isInternal(topic), util.Collections.emptyList()))

Review comment:
       Quick question. Do we also set topic null when we have actual unknown topic IDs?




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r546309738



##########
File path: clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
##########
@@ -343,7 +344,8 @@
     INVALID_UPDATE_VERSION(95, "The given update version was invalid.", InvalidUpdateVersionException::new),
     FEATURE_UPDATE_FAILED(96, "Unable to update finalized features due to an unexpected server error.", FeatureUpdateFailedException::new),
     PRINCIPAL_DESERIALIZATION_FAILURE(97, "Request principal deserialization failed during forwarding. " +
-         "This indicates an internal error on the broker cluster security setup.", PrincipalDeserializationException::new);
+         "This indicates an internal error on the broker cluster security setup.", PrincipalDeserializationException::new),
+    UNKNOWN_TOPIC_ID(98, "The topic ID dose not exist", UnknownTopicIdException::new);

Review comment:
       Thank you, I think your message may be more appropriate.




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-766972011


   I added a few comments. Mostly just questions for clarification.


----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-763996884


   @dengziming https://github.com/apache/kafka/pull/9814 has been merged, so this needs rebasing and the check for IBP. Thanks.


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r564638290



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1247,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), false, util.Collections.emptyList()))

Review comment:
       Thanks for fixing this!
   




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-817051364


   @rajinisivaram @jolshan , Currently we have startd merge pr for 3.0, so it's time to take a look at this again, also #9684 since part of it has been reverted, thank you.


-- 
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r551607061



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1238,8 +1239,21 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)

Review comment:
       Hey, with the new addition of gating topic IDs behind IBP 2.8, can we do a check of the interbroker protocol version in this method and if it is not at least 2.8, return with UNSUPPORTED_VERSION error. There is a method in the 2.8 PR to easily get this information: `KafkaConfig.usesTopicId`
   
   Here's the other PR for reference: https://github.com/apache/kafka/pull/9814
   Here's the KIP with the updated error behavior: https://cwiki.apache.org/confluence/display/KAFKA/KIP-516%3A+Topic+Identifiers#KIP516:TopicIdentifiers-AdminandKafkaAdminClient
   
   I will update the delete topics logic to follow this behavior as well. 




----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-769809654


   @dengziming Sorry missed your note. Will wait for the current build to complete in case it was a timing issue due to slow machines. Agree that the issues don't look related to this PR, if the tests still fail, I will verify locally and merge. Thanks.


----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-769771773


   @rajinisivaram I triggered the QA again but still has some failures, it seems the failure is unrelated to this pr since other PRs also have these failures.


----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r664306577



##########
File path: core/src/main/scala/kafka/api/ApiVersion.scala
##########
@@ -116,7 +116,9 @@ object ApiVersion {
     // Introduce AllocateProducerIds (KIP-730)
     KAFKA_3_0_IV0,
     // Introduce ListOffsets V7 which supports listing offsets by max timestamp (KIP-734)
-    KAFKA_3_0_IV1
+    KAFKA_3_0_IV1,
+    // Introduced topic IDs to MetadataRequest

Review comment:
       You are right, we no longer need to check UNSUPPORTED_VERSION_ERROR, so it's unnecessary to bump IBP.

##########
File path: clients/src/main/resources/common/message/MetadataResponse.json
##########
@@ -65,7 +66,7 @@
       "about": "Each topic in the response.", "fields": [
       { "name": "ErrorCode", "type": "int16", "versions": "0+",
         "about": "The topic error, or 0 if there was no error." },
-      { "name": "Name", "type": "string", "versions": "0+", "mapKey": true, "entityType": "topicName",
+      { "name": "Name", "type": "string", "versions": "0+", "mapKey": true, "entityType": "topicName", "nullableVersions": "10+",

Review comment:
       Yes, this should be 12+

##########
File path: clients/src/main/java/org/apache/kafka/common/requests/MetadataRequest.java
##########
@@ -65,6 +65,20 @@ public Builder(List<String> topics, boolean allowAutoTopicCreation) {
             this(topics, allowAutoTopicCreation, ApiKeys.METADATA.oldestVersion(),  ApiKeys.METADATA.latestVersion());
         }
 
+        public Builder(List<Uuid> topicIds) {
+            super(ApiKeys.METADATA, ApiKeys.METADATA.oldestVersion(), ApiKeys.METADATA.latestVersion());
+            MetadataRequestData data = new MetadataRequestData();
+            if (topicIds == null)
+                data.setTopics(null);
+            else {
+                topicIds.forEach(topicId -> data.topics().add(new MetadataRequestTopic().setTopicId(topicId).setName("")));

Review comment:
       This is old code since we do not support null names firstly, now we can remove this useless code.

##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -32,28 +34,87 @@
  */
 @InterfaceStability.Evolving
 public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+    private final Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures;
+    private final Map<String, KafkaFuture<TopicDescription>> nameFutures;
 
-    protected DescribeTopicsResult(Map<String, KafkaFuture<TopicDescription>> futures) {
-        this.futures = futures;
+    protected DescribeTopicsResult(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures, Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        if (topicIdFutures != null && nameFutures != null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be specified.");
+        if (topicIdFutures == null && nameFutures == null)
+            throw new IllegalArgumentException("topicIdFutures and nameFutures cannot both be null.");
+        this.topicIdFutures = topicIdFutures;
+        this.nameFutures = nameFutures;
+    }
+
+    static DescribeTopicsResult ofTopicIds(Map<Uuid, KafkaFuture<TopicDescription>> topicIdFutures) {
+        return new DescribeTopicsResult(topicIdFutures, null);
+    }
+
+    static DescribeTopicsResult ofTopicNames(Map<String, KafkaFuture<TopicDescription>> nameFutures) {
+        return new DescribeTopicsResult(null, nameFutures);
+    }
+
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicIdCollection
+     *
+     * @return a map from topic IDs to futures which can be used to check the status of
+     *         individual topics if the request used topic IDs, otherwise return null.
+     */
+    public Map<Uuid, KafkaFuture<TopicDescription>> topicIdValues() {
+        return topicIdFutures;
     }
 
+    /**
+     * Use when {@link Admin#describeTopics(TopicCollection, DescribeTopicsOptions)} used a TopicNameCollection
+     *
+     * @return a map from topic names to futures which can be used to check the status of
+     *         individual topics if the request used topic names, otherwise return null.
+     */
+    public Map<String, KafkaFuture<TopicDescription>> topicNameValues() {
+        return nameFutures;
+    }
+
+
     /**
      * Return a map from topic names to futures which can be used to check the status of
      * individual topics.
      */
+    @Deprecated
     public Map<String, KafkaFuture<TopicDescription>> values() {
-        return futures;
+        return nameFutures;
     }
 
     /**
      * Return a future which succeeds only if all the topic descriptions succeed.
      */
     public KafkaFuture<Map<String, TopicDescription>> all() {
-        return KafkaFuture.allOf(futures.values().toArray(new KafkaFuture[0])).
+        return all(nameFutures);

Review comment:
       Done, and also change all usages to use `allTopicNames()`.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] rajinisivaram commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-769702522


   @dengziming Thanks for the update. Looks like there is an issue with the tests in the last commit (see test failures in the PR build).


----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563708864



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,117 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_2_8_IV1)

Review comment:
       Firstly I add 2 brokers to ensure faster election after killing the broker, now I added a broker since we need not kill broker to trigger election.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r564224916



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1247,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, metadataCache.getTopicId(topic), false, util.Collections.emptyList()))

Review comment:
       I checked the error responses and found that we should hide TopicId when error=`TOPIC_AUTHORIZATION_FAILED`, and we can respond topicId on other errors.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r567718317



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1191,8 +1192,35 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    // Check if topicId is presented firstly.
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
+    val useTopicId = topicIds.nonEmpty
+
+    val (supportedVersionTopicIds, unsupportedVersionTopicIds) = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1)
+      (topicIds, Set.empty[Uuid])
+    else
+      (Set.empty[Uuid], topicIds)
+
+    val unsupportedVersionTopicMetadata = if (unsupportedVersionTopicIds.isEmpty)
+      Seq.empty[MetadataResponseTopic]
+    else
+      unsupportedVersionTopicIds.map(topicId =>
+        metadataResponseTopic(Errors.UNSUPPORTED_VERSION, null, topicId, false, util.Collections.emptyList())).toSeq
+
+    // Only get topicIds and topicNames when supporting topicId
+    val unknownTopicIds = supportedVersionTopicIds.filter(metadataCache.getTopicName(_).isEmpty)
+    val knownTopicNames = supportedVersionTopicIds.flatMap(metadataCache.getTopicName)
+
+    val unknownTopicIdsTopicMetadata = if (unknownTopicIds.isEmpty)
+      Seq.empty[MetadataResponseTopic]
+    else
+      unknownTopicIds.map(topicId =>
+        metadataResponseTopic(Errors.UNKNOWN_TOPIC_ID, null, topicId, false, util.Collections.emptyList())).toSeq
+
     val topics = if (metadataRequest.isAllTopics)
       metadataCache.getAllTopics()
+    else if (useTopicId)

Review comment:
       According to KIP-516, we just ignore topic name if a none zero topic id is provided. 




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r665814181



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,103 @@
+/**
+  * 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.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_3_0_IV1}
+import kafka.network.SocketServer
+import kafka.utils.TestUtils
+import kafka.zk.ZkVersion
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_3_0_IV1),
+      createConfig(2, KAFKA_3_0_IV1)
+    )
+  }
+
+  @Test
+  def testUnknownTopicId(): Unit = {
+    val topic = "topic"
+
+    // Kill controller and restart until broker 2 become controller
+    ensureControllerIn(Seq(1, 2))
+    createTopic(topic, Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 12.toShort), controllerSocketServer)
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+
+    // We could still get topic metadata by topicId
+   val topicMetadata = sendMetadataRequest(new MetadataRequest(requestData(null, topicId), 12.toShort), controllerSocketServer)
+      .topicMetadata.iterator().next()
+    assertEquals(topicId, topicMetadata.topicId())
+    assertEquals(topic, topicMetadata.topic())
+
+    // Make the broker whose version=KAFKA_3_0_IV0 controller

Review comment:
       This class is created to test the 2 cases here: https://github.com/apache/kafka/pull/9769#discussion_r562511974 , and now we only need to test the `UNKNOWN_TOPIC_ID` case since we do not need `UNSUPPORTED_VERSION` now.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] rajinisivaram commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-770115726


   @dengziming I am so sorry, I didn't notice that you had updated the branch a few minutes ago, so force-pushed my version. Do you mind force-pushing your branch once more please?


----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r562394749



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
##########
@@ -1822,6 +1829,88 @@ void handleFailure(Throwable throwable) {
         return new DescribeTopicsResult(new HashMap<>(topicFutures));
     }
 
+    @Override
+    public DescribeTopicsResultWithIds describeTopicsWithIds(Collection<Uuid> topicIds, DescribeTopicsOptions options) {
+
+        final Map<Uuid, KafkaFutureImpl<TopicDescription>> topicFutures = new HashMap<>(topicIds.size());
+        final List<Uuid> topicIdsList = new ArrayList<>();
+        for (Uuid topicId : topicIds) {
+            if (topicIdIsUnrepresentable(topicId)) {
+                KafkaFutureImpl<TopicDescription> future = new KafkaFutureImpl<>();
+                future.completeExceptionally(new InvalidTopicException("The given topic id '" +
+                        topicId + "' cannot be represented in a request."));
+                topicFutures.put(topicId, future);
+            } else if (!topicFutures.containsKey(topicId)) {
+                topicFutures.put(topicId, new KafkaFutureImpl<>());
+                topicIdsList.add(topicId);
+            }
+        }
+        final long now = time.milliseconds();
+        Call call = new Call("describeTopicsWithIds", calcDeadlineMs(now, options.timeoutMs()),
+                new LeastLoadedNodeProvider()) {
+
+            @Override
+            MetadataRequest.Builder createRequest(int timeoutMs) {
+                return new MetadataRequest.Builder(new MetadataRequestData()
+                        .setTopics(convertTopicIdsToMetadataRequestTopic(topicIdsList))
+                        .setAllowAutoTopicCreation(false)
+                        .setIncludeTopicAuthorizedOperations(options.includeAuthorizedOperations()));
+            }
+
+            @Override
+            void handleResponse(AbstractResponse abstractResponse) {
+                MetadataResponse response = (MetadataResponse) abstractResponse;
+                // Handle server responses for particular topics.
+                Cluster cluster = response.cluster();
+                Map<Uuid, Errors> errors = response.errorsByTopicId();
+                for (Map.Entry<Uuid, KafkaFutureImpl<TopicDescription>> entry : topicFutures.entrySet()) {
+                    Uuid topicId = entry.getKey();
+                    KafkaFutureImpl<TopicDescription> future = entry.getValue();
+
+                    String topicName = cluster.topicName(topicId);
+                    if (topicName == null) {
+                        future.completeExceptionally(new UnknownTopicIdException("TopicId " + topicId + " not found."));
+                        continue;
+                    }
+                    Errors topicError = errors.get(topicId);
+                    if (topicError != null) {
+                        future.completeExceptionally(topicError.exception());
+                        continue;
+                    }
+
+                    boolean isInternal = cluster.internalTopics().contains(topicName);
+                    List<PartitionInfo> partitionInfos = cluster.partitionsForTopic(topicName);
+                    List<TopicPartitionInfo> partitions = new ArrayList<>(partitionInfos.size());
+                    for (PartitionInfo partitionInfo : partitionInfos) {
+                        TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(
+                                partitionInfo.partition(), leader(partitionInfo), Arrays.asList(partitionInfo.replicas()),
+                                Arrays.asList(partitionInfo.inSyncReplicas()));
+                        partitions.add(topicPartitionInfo);
+                    }
+                    partitions.sort(Comparator.comparingInt(TopicPartitionInfo::partition));
+                    TopicDescription topicDescription = new TopicDescription(topicName, isInternal, partitions,
+                            validAclOperations(response.topicAuthorizedOperations(topicName).get()), topicId);
+                    future.complete(topicDescription);

Review comment:
       Thank you, I added a getTopicDescriptionFromCluster to do this.




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r664077354



##########
File path: clients/src/main/resources/common/message/MetadataResponse.json
##########
@@ -65,7 +66,7 @@
       "about": "Each topic in the response.", "fields": [
       { "name": "ErrorCode", "type": "int16", "versions": "0+",
         "about": "The topic error, or 0 if there was no error." },
-      { "name": "Name", "type": "string", "versions": "0+", "mapKey": true, "entityType": "topicName",
+      { "name": "Name", "type": "string", "versions": "0+", "mapKey": true, "entityType": "topicName", "nullableVersions": "10+",

Review comment:
       can we set a previous version to be nullable? Or does this need to be 12+




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r611214209



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1165,16 +1189,23 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
+      // Set topicId to zero since we will never create topic which topicId
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, Uuid.ZERO_UUID, isInternal(topic), util.Collections.emptyList()))
 
     // do not disclose the existence of topics unauthorized for Describe, so we've not even checked if they exist or not
     val unauthorizedForDescribeTopicMetadata =
       // In case of all topics, don't include topics unauthorized for Describe
       if ((requestVersion == 0 && (metadataRequest.topics == null || metadataRequest.topics.isEmpty)) || metadataRequest.isAllTopics)
         Set.empty[MetadataResponseTopic]
-      else
+      else if (useTopicId) {
+        // We should not return information about existence of a topic on unauthorized error, so we return an UNKNOWN_TOPIC_ID
+        unauthorizedForDescribeTopics.map(topic =>
+          metadataResponseTopic(Errors.UNKNOWN_TOPIC_ID, null, metadataCache.getTopicId(topic), false, util.Collections.emptyList()))

Review comment:
       In the time since we last looked at this, we decided that it is ok to acknowledge existence of the topic ID and return TOPIC_AUTHORIZATION_FAILED. This is so the client knows it is not a retriable error. Please see https://issues.apache.org/jira/browse/KAFKA-12394 for more details. 




-- 
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563708864



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,117 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_2_8_IV1)

Review comment:
       Firstly I add 2 brokers to ensure faster election after killing broker, now I added a broker since we need not kill broker to trigger election.

##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,117 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_2_8_IV1)

Review comment:
       Firstly I add 2 brokers to ensure faster election after killing the broker, now I added a broker since we need not kill broker to trigger election.

##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,117 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_2_8_IV1)
+    )
+  }
+
+  @Test
+  def testTopicIdUnsupported(): Unit = {
+
+    val topic = "topic"
+
+    // Ensure controller version = KAFKA_2_8_IV1, and then create a topic
+    ensureControllerIn(Seq(1))
+    createTopic(topic,  Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    // We can get topicId from the controller
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), brokerSocketServer(1))
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+    assertNotEquals(Uuid.ZERO_UUID, topicId)
+    assertNotNull(topicId)
+
+    // Send request to a broker whose version=KAFKA_2_8_IV0
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(0))
+    assertEquals(Errors.UNSUPPORTED_VERSION, resp2.topicMetadata.iterator().next().error())
+  }
+
+  @Test
+  def testUnknownTopicId(): Unit = {
+
+    val topic = "topic"
+
+    // Kill controller and restart until broker 2 become controller
+    ensureControllerIn(Seq(1))
+    createTopic(topic, Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), brokerSocketServer(1))
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+
+    // We could still get topic metadata by topicId
+    val topicMetadata = sendMetadataRequest(new MetadataRequest(requestData(null, topicId), 10.toShort), brokerSocketServer(1))
+      .topicMetadata.iterator().next()
+    assertEquals(topicId, topicMetadata.topicId())
+    assertEquals(topic, topicMetadata.topic())
+
+    // Make the broker whose version=KAFKA_2_8_IV0 controller
+    ensureControllerIn(Seq(0))
+
+    // Restart the broker whose version=KAFKA_2_8_IV1, and the controller will send metadata request to it
+    killBroker(1)
+    restartDeadBrokers()
+
+    // Send request to a broker whose version=KAFKA_2_8_IV1
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(1))
+    assertEquals(Errors.UNKNOWN_TOPIC_ID, resp2.topicMetadata.iterator().next().error())
+  }
+
+  private def ensureControllerIn(brokerIds: Seq[Int]): Unit = {
+    while (!brokerIds.contains(controllerSocketServer.config.brokerId)) {
+      killBroker(controllerSocketServer.config.brokerId)

Review comment:
       Good catch, updated.




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r551633181



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
##########
@@ -1816,7 +1823,103 @@ void handleFailure(Throwable throwable) {
         if (!topicNamesList.isEmpty()) {
             runnable.call(call, now);
         }
-        return new DescribeTopicsResult(new HashMap<>(topicFutures));
+        return new DescribeTopicsResult<>(new HashMap<>(topicFutures));
+    }
+
+    @Override
+    public DescribeTopicsResult<Uuid> describeTopicsWithIds(Collection<Uuid> topicIds, DescribeTopicsOptions options) {
+
+        final Map<Uuid, KafkaFutureImpl<TopicDescription>> topicFutures = new HashMap<>(topicIds.size());
+        final List<Uuid> topicIdsList = new ArrayList<>();
+        for (Uuid topicId : topicIds) {
+            if (topicIdIsUnrepresentable(topicId)) {

Review comment:
       We might want to do the IBP check here to and complete exceptionally with UnsupportedVersion error with a message about topic IDs only in IBP 2.8 and above. 




----------------------------------------------------------------
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



[GitHub] [kafka] chia7712 commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
chia7712 commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r567655022



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/TopicListing.java
##########
@@ -17,24 +17,36 @@
 
 package org.apache.kafka.clients.admin;
 
+import org.apache.kafka.common.Uuid;
+
 /**
  * A listing of a topic in the cluster.
  */
 public class TopicListing {
     private final String name;
+    private final Uuid topicId;
     private final boolean internal;
 
     /**
      * Create an instance with the specified parameters.
      *
      * @param name The topic name
+     * @param topicId The topic id.
      * @param internal Whether the topic is internal to Kafka
      */
-    public TopicListing(String name, boolean internal) {
+    public TopicListing(String name, Uuid topicId, boolean internal) {
+        this.topicId = topicId;
         this.name = name;
         this.internal = internal;
     }
 
+    /**
+     * The id of the topic.
+     */
+    public Uuid topicId() {

Review comment:
       Could you add topic id to ```toString```?

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1191,8 +1192,35 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    // Check if topicId is presented firstly.
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
+    val useTopicId = topicIds.nonEmpty
+
+    val (supportedVersionTopicIds, unsupportedVersionTopicIds) = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1)
+      (topicIds, Set.empty[Uuid])
+    else
+      (Set.empty[Uuid], topicIds)
+
+    val unsupportedVersionTopicMetadata = if (unsupportedVersionTopicIds.isEmpty)
+      Seq.empty[MetadataResponseTopic]
+    else
+      unsupportedVersionTopicIds.map(topicId =>
+        metadataResponseTopic(Errors.UNSUPPORTED_VERSION, null, topicId, false, util.Collections.emptyList())).toSeq
+
+    // Only get topicIds and topicNames when supporting topicId
+    val unknownTopicIds = supportedVersionTopicIds.filter(metadataCache.getTopicName(_).isEmpty)
+    val knownTopicNames = supportedVersionTopicIds.flatMap(metadataCache.getTopicName)
+
+    val unknownTopicIdsTopicMetadata = if (unknownTopicIds.isEmpty)

Review comment:
       ```scala
       val unknownTopicIdsTopicMetadata = unknownTopicIds.map(topicId =>
           metadataResponseTopic(Errors.UNKNOWN_TOPIC_ID, null, topicId, false, util.Collections.emptyList())).toSeq
   ```
   
   Is above code more simple?

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1191,8 +1192,35 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    // Check if topicId is presented firstly.
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
+    val useTopicId = topicIds.nonEmpty
+
+    val (supportedVersionTopicIds, unsupportedVersionTopicIds) = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1)
+      (topicIds, Set.empty[Uuid])
+    else
+      (Set.empty[Uuid], topicIds)
+
+    val unsupportedVersionTopicMetadata = if (unsupportedVersionTopicIds.isEmpty)

Review comment:
       ```scala
       val unsupportedVersionTopicMetadata = unsupportedVersionTopicIds.map(topicId =>
           metadataResponseTopic(Errors.UNSUPPORTED_VERSION, null, topicId, false, util.Collections.emptyList())).toSeq
   ```
   
   Is above code more simple?

##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1191,8 +1192,35 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    // Check if topicId is presented firstly.
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)
+    val useTopicId = topicIds.nonEmpty
+
+    val (supportedVersionTopicIds, unsupportedVersionTopicIds) = if (config.interBrokerProtocolVersion >= KAFKA_2_8_IV1)
+      (topicIds, Set.empty[Uuid])
+    else
+      (Set.empty[Uuid], topicIds)
+
+    val unsupportedVersionTopicMetadata = if (unsupportedVersionTopicIds.isEmpty)
+      Seq.empty[MetadataResponseTopic]
+    else
+      unsupportedVersionTopicIds.map(topicId =>
+        metadataResponseTopic(Errors.UNSUPPORTED_VERSION, null, topicId, false, util.Collections.emptyList())).toSeq
+
+    // Only get topicIds and topicNames when supporting topicId
+    val unknownTopicIds = supportedVersionTopicIds.filter(metadataCache.getTopicName(_).isEmpty)
+    val knownTopicNames = supportedVersionTopicIds.flatMap(metadataCache.getTopicName)
+
+    val unknownTopicIdsTopicMetadata = if (unknownTopicIds.isEmpty)
+      Seq.empty[MetadataResponseTopic]
+    else
+      unknownTopicIds.map(topicId =>
+        metadataResponseTopic(Errors.UNKNOWN_TOPIC_ID, null, topicId, false, util.Collections.emptyList())).toSeq
+
     val topics = if (metadataRequest.isAllTopics)
       metadataCache.getAllTopics()
+    else if (useTopicId)

Review comment:
       Should we reject the requests carrying both topic id and topic name?




----------------------------------------------------------------
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



[GitHub] [kafka] rajinisivaram commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
rajinisivaram commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-771612611


   Looks like a bug was introduced by a different PR, opened https://issues.apache.org/jira/browse/KAFKA-12268 to fix this.


----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-887949936


   @rajinisivaram Are you interested in taking this across finish line? I think this has something that is very close to a first version, we can try to land that and then improvise since this has been worked for a long time, thank you!


-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r556437337



##########
File path: clients/src/test/java/org/apache/kafka/clients/admin/MockAdminClient.java
##########
@@ -206,6 +209,8 @@ synchronized public void addTopic(boolean internal,
                 logDirs.add(brokerLogDirs.get(partition.leader().id()).get(0));
             }
         }
+        Uuid topicId = Uuid.randomUuid();
+        topicIds.put(name, topicId);

Review comment:
       Currently, MockAdminClient is mainly used in connect module and stream module, we could add another ticket to do this.   




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563880732



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,125 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import kafka.zk.ZkVersion
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {

Review comment:
       This test is super cool and will be very useful when testing other request types like fetch. 




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-769200848


   Thanks for the update. The test case is good. In general, LGTM


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r565575532



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1223,7 +1251,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         Set.empty[MetadataResponseTopic]
       else
         unauthorizedForDescribeTopics.map(topic =>
-          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, false, util.Collections.emptyList()))
+          metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, Uuid.ZERO_UUID, false, util.Collections.emptyList()))

Review comment:
       So will we never reach this code path when using topic IDs? I think we are using topics to decide authorization. So in the case where we use ids and the name exists, then we will expose the name and return a zero ID? Might be useful to create an authorizer integration test with topic IDs to ensure correctness.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r556175816



##########
File path: clients/src/main/java/org/apache/kafka/clients/admin/DescribeTopicsResult.java
##########
@@ -31,29 +31,29 @@
  * The API of this class is evolving, see {@link Admin} for details.
  */
 @InterfaceStability.Evolving
-public class DescribeTopicsResult {
-    private final Map<String, KafkaFuture<TopicDescription>> futures;
+public class DescribeTopicsResult<T> {

Review comment:
       Thank you for your reminder, I have rollbacked all the public API change.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-863736540


   Check KAFKA-12701 and bump the version of the MetadataRequest/MetadataResponse, @rajinisivaram @jolshan PTAL.


-- 
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r611214209



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1165,16 +1189,23 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
 
     val unauthorizedForCreateTopicMetadata = unauthorizedForCreateTopics.map(topic =>
-      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, isInternal(topic), util.Collections.emptyList()))
+      // Set topicId to zero since we will never create topic which topicId
+      metadataResponseTopic(Errors.TOPIC_AUTHORIZATION_FAILED, topic, Uuid.ZERO_UUID, isInternal(topic), util.Collections.emptyList()))
 
     // do not disclose the existence of topics unauthorized for Describe, so we've not even checked if they exist or not
     val unauthorizedForDescribeTopicMetadata =
       // In case of all topics, don't include topics unauthorized for Describe
       if ((requestVersion == 0 && (metadataRequest.topics == null || metadataRequest.topics.isEmpty)) || metadataRequest.isAllTopics)
         Set.empty[MetadataResponseTopic]
-      else
+      else if (useTopicId) {
+        // We should not return information about existence of a topic on unauthorized error, so we return an UNKNOWN_TOPIC_ID
+        unauthorizedForDescribeTopics.map(topic =>
+          metadataResponseTopic(Errors.UNKNOWN_TOPIC_ID, null, metadataCache.getTopicId(topic), false, util.Collections.emptyList()))

Review comment:
       In the time since we last looked at this, we decided that it is ok to acknowledge existence of the topic ID and return TOPIC_AUTHORIZATION_FAILED. This is so the user knows it is not a retriable error. Please see https://issues.apache.org/jira/browse/KAFKA-12394 for more details. 




-- 
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r551607061



##########
File path: core/src/main/scala/kafka/server/KafkaApis.scala
##########
@@ -1238,8 +1239,21 @@ class KafkaApis(val requestChannel: RequestChannel,
     val metadataRequest = request.body[MetadataRequest]
     val requestVersion = request.header.apiVersion
 
+    val topicIds = metadataRequest.topicIds.asScala.toSet.filterNot(_ == Uuid.ZERO_UUID)

Review comment:
       Hey, with the new addition of gating topic IDs behind IBP 2.8, can we do a check of the interbroker protocol version in this method and if it is not at least 2.8, return with UNSUPPORTED_VERSION error with a message about topic IDs only in IBP 2.8 and above. There is a method in the 2.8 PR to easily get this information: `KafkaConfig.usesTopicId`
   
   Here's the other PR for reference: https://github.com/apache/kafka/pull/9814
   Here's the KIP with the updated error behavior: https://cwiki.apache.org/confluence/display/KAFKA/KIP-516%3A+Topic+Identifiers#KIP516:TopicIdentifiers-AdminandKafkaAdminClient
   
   I will update the delete topics logic to follow this behavior as well. 




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r564979586



##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -313,42 +314,59 @@ object TopicCommand extends Logging {
     }
 
     override def describeTopic(opts: TopicCommandOptions): Unit = {
-      val topics = getTopics(opts.topic, opts.excludeInternalTopics)
-      ensureTopicExists(topics, opts.topic, !opts.ifExists)
+      // if topicId is provided and not zero, will use topicId regardless of topic name
+      val useTopicId = opts.topicId.map(Uuid.fromString).nonEmpty

Review comment:
       Thank you, I was careless about this case, I add the following fix:
   1. When --topic and --topic-id are both specified, I will print a warning message that saying that "topicId will be used if both are specified and topicId is not zero"
   2. Filter ZERO UUID before handling in TopicCommand.




----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563861257



##########
File path: core/src/main/scala/kafka/admin/TopicCommand.scala
##########
@@ -313,42 +313,57 @@ object TopicCommand extends Logging {
     }
 
     override def describeTopic(opts: TopicCommandOptions): Unit = {
-      val topics = getTopics(opts.topic, opts.excludeInternalTopics)
-      ensureTopicExists(topics, opts.topic, !opts.ifExists)
+      val topicId = opts.topicId.map(Uuid.fromString).filter(_ != Uuid.ZERO_UUID)
+      // if topicId is provided and not zero, will use topicId regardless of topic name

Review comment:
       I don't have an issue with this, but just curious why this was chosen over failing.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-770140196


   The 2 failures in https://ci-builds.apache.org/job/Kafka/job/kafka-pr/job/PR-9769/22/ seem to be related to Mockito, maybe #10006 will fix it. @rajinisivaram PTAL.


----------------------------------------------------------------
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



[GitHub] [kafka] jolshan commented on pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
jolshan commented on pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#issuecomment-874862869


   Looks like some deprecated methods should be replaced.
   ```
    /home/jenkins/jenkins-agent/workspace/Kafka_kafka-pr_PR-9769/connect/mirror/src/main/java/org/apache/kafka/connect/mirror/MirrorSourceConnector.java:402: warning: 
   
   [deprecation] all() in org.apache.kafka.clients.admin.DescribeTopicsResult has been deprecated
    ```


-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r563709244



##########
File path: core/src/test/scala/integration/kafka/server/MetadataRequestBetweenDifferentIbpTest.scala
##########
@@ -0,0 +1,117 @@
+/**
+  * 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 integration.kafka.server
+
+import kafka.api.{ApiVersion, KAFKA_2_8_IV0, KAFKA_2_8_IV1}
+import kafka.network.SocketServer
+import kafka.server.{BaseRequestTest, KafkaConfig}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.Uuid
+import org.apache.kafka.common.message.MetadataRequestData
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.{MetadataRequest, MetadataResponse}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.Test
+
+import scala.collection.{Map, Seq}
+
+class MetadataRequestBetweenDifferentIbpTest extends BaseRequestTest {
+
+  override def brokerCount: Int = 3
+  override def generateConfigs: Seq[KafkaConfig] = {
+    Seq(
+      createConfig(0, KAFKA_2_8_IV0),
+      createConfig(1, KAFKA_2_8_IV1)
+    )
+  }
+
+  @Test
+  def testTopicIdUnsupported(): Unit = {
+
+    val topic = "topic"
+
+    // Ensure controller version = KAFKA_2_8_IV1, and then create a topic
+    ensureControllerIn(Seq(1))
+    createTopic(topic,  Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    // We can get topicId from the controller
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), brokerSocketServer(1))
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+    assertNotEquals(Uuid.ZERO_UUID, topicId)
+    assertNotNull(topicId)
+
+    // Send request to a broker whose version=KAFKA_2_8_IV0
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(0))
+    assertEquals(Errors.UNSUPPORTED_VERSION, resp2.topicMetadata.iterator().next().error())
+  }
+
+  @Test
+  def testUnknownTopicId(): Unit = {
+
+    val topic = "topic"
+
+    // Kill controller and restart until broker 2 become controller
+    ensureControllerIn(Seq(1))
+    createTopic(topic, Map(0 -> Seq(1, 2, 0), 1 -> Seq(2, 0, 1)))
+
+    val resp1 = sendMetadataRequest(new MetadataRequest(requestData(topic, Uuid.ZERO_UUID), 10.toShort), brokerSocketServer(1))
+    val topicId = resp1.topicMetadata.iterator().next().topicId()
+
+    // We could still get topic metadata by topicId
+    val topicMetadata = sendMetadataRequest(new MetadataRequest(requestData(null, topicId), 10.toShort), brokerSocketServer(1))
+      .topicMetadata.iterator().next()
+    assertEquals(topicId, topicMetadata.topicId())
+    assertEquals(topic, topicMetadata.topic())
+
+    // Make the broker whose version=KAFKA_2_8_IV0 controller
+    ensureControllerIn(Seq(0))
+
+    // Restart the broker whose version=KAFKA_2_8_IV1, and the controller will send metadata request to it
+    killBroker(1)
+    restartDeadBrokers()
+
+    // Send request to a broker whose version=KAFKA_2_8_IV1
+    val resp2 = sendMetadataRequest(new MetadataRequest(requestData(topic, topicId), 10.toShort), brokerSocketServer(1))
+    assertEquals(Errors.UNKNOWN_TOPIC_ID, resp2.topicMetadata.iterator().next().error())
+  }
+
+  private def ensureControllerIn(brokerIds: Seq[Int]): Unit = {
+    while (!brokerIds.contains(controllerSocketServer.config.brokerId)) {
+      killBroker(controllerSocketServer.config.brokerId)

Review comment:
       Good catch, updated.




----------------------------------------------------------------
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



[GitHub] [kafka] dengziming commented on a change in pull request #9769: KAFKA-10774; Support Describe topic using topic IDs

Posted by GitBox <gi...@apache.org>.
dengziming commented on a change in pull request #9769:
URL: https://github.com/apache/kafka/pull/9769#discussion_r664308959



##########
File path: clients/src/main/java/org/apache/kafka/common/requests/MetadataRequest.java
##########
@@ -65,6 +65,20 @@ public Builder(List<String> topics, boolean allowAutoTopicCreation) {
             this(topics, allowAutoTopicCreation, ApiKeys.METADATA.oldestVersion(),  ApiKeys.METADATA.latestVersion());
         }
 
+        public Builder(List<Uuid> topicIds) {
+            super(ApiKeys.METADATA, ApiKeys.METADATA.oldestVersion(), ApiKeys.METADATA.latestVersion());
+            MetadataRequestData data = new MetadataRequestData();
+            if (topicIds == null)
+                data.setTopics(null);
+            else {
+                topicIds.forEach(topicId -> data.topics().add(new MetadataRequestTopic().setTopicId(topicId).setName("")));

Review comment:
       This is old code since we do not support null names firstly, now we can remove this useless code.




-- 
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.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

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