You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kafka.apache.org by jg...@apache.org on 2022/06/15 16:20:26 UTC
[kafka] branch trunk updated: KAFKA-13888; Addition of Information in DescribeQuorumResponse about Voter Lag (#12206)
This is an automated email from the ASF dual-hosted git repository.
jgus pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/kafka.git
The following commit(s) were added to refs/heads/trunk by this push:
new a126e3a622 KAFKA-13888; Addition of Information in DescribeQuorumResponse about Voter Lag (#12206)
a126e3a622 is described below
commit a126e3a622f2b7142f3543b9dbee54b6412ba9d8
Author: Niket <ni...@users.noreply.github.com>
AuthorDate: Wed Jun 15 09:20:15 2022 -0700
KAFKA-13888; Addition of Information in DescribeQuorumResponse about Voter Lag (#12206)
This commit adds an Admin API handler for DescribeQuorum Request and also
adds in two new fields LastFetchTimestamp and LastCaughtUpTimestamp to
the DescribeQuorumResponse as described by KIP-836.
This commit does not implement the newly added fields. Those will be
added in a subsequent commit.
Reviewers: dengziming <de...@gmail.com>, David Jacot <dj...@confluent.io>, Jason Gustafson <ja...@confluent.io>
---
.../java/org/apache/kafka/clients/admin/Admin.java | 29 ++++
.../admin/DescribeMetadataQuorumOptions.java | 24 ++++
.../admin/DescribeMetadataQuorumResult.java | 38 +++++
.../kafka/clients/admin/KafkaAdminClient.java | 85 ++++++++++++
.../org/apache/kafka/clients/admin/QuorumInfo.java | 153 +++++++++++++++++++++
.../org/apache/kafka/common/internals/Topic.java | 3 +
.../common/message/DescribeQuorumRequest.json | 3 +-
.../common/message/DescribeQuorumResponse.json | 9 +-
.../kafka/clients/admin/KafkaAdminClientTest.java | 136 ++++++++++++++++++
.../kafka/clients/admin/MockAdminClient.java | 5 +
.../main/scala/kafka/server/KafkaRaftServer.scala | 7 +-
.../kafka/server/DescribeQuorumRequestTest.scala | 64 +++++----
12 files changed, 524 insertions(+), 32 deletions(-)
diff --git a/clients/src/main/java/org/apache/kafka/clients/admin/Admin.java b/clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
index 0c795bc520..fdacc09db8 100644
--- a/clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
+++ b/clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
@@ -1446,6 +1446,35 @@ public interface Admin extends AutoCloseable {
*/
UpdateFeaturesResult updateFeatures(Map<String, FeatureUpdate> featureUpdates, UpdateFeaturesOptions options);
+ /**
+ * Describes the state of the metadata quorum.
+ * <p>
+ * This is a convenience method for {@link #describeMetadataQuorum(DescribeMetadataQuorumOptions)} with default options.
+ * See the overload for more details.
+ *
+ * @return the {@link DescribeMetadataQuorumResult} containing the result
+ */
+ default DescribeMetadataQuorumResult describeMetadataQuorum() {
+ return describeMetadataQuorum(new DescribeMetadataQuorumOptions());
+ }
+
+ /**
+ * Describes the state of the metadata quorum.
+ * <p>
+ * The following exceptions can be anticipated when calling {@code get()} on the futures obtained from
+ * the returned {@code DescribeMetadataQuorumResult}:
+ * <ul>
+ * <li>{@link org.apache.kafka.common.errors.ClusterAuthorizationException}
+ * If the authenticated user didn't have {@code DESCRIBE} access to the cluster.</li>
+ * <li>{@link org.apache.kafka.common.errors.TimeoutException}
+ * If the request timed out before the controller could list the cluster links.</li>
+ * </ul>
+ *
+ * @param options The {@link DescribeMetadataQuorumOptions} to use when describing the quorum.
+ * @return the {@link DescribeMetadataQuorumResult} containing the result
+ */
+ DescribeMetadataQuorumResult describeMetadataQuorum(DescribeMetadataQuorumOptions options);
+
/**
* Unregister a broker.
* <p>
diff --git a/clients/src/main/java/org/apache/kafka/clients/admin/DescribeMetadataQuorumOptions.java b/clients/src/main/java/org/apache/kafka/clients/admin/DescribeMetadataQuorumOptions.java
new file mode 100644
index 0000000000..8f54cc81f2
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/clients/admin/DescribeMetadataQuorumOptions.java
@@ -0,0 +1,24 @@
+/*
+ * 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.clients.admin;
+
+/**
+ * Options for {@link Admin#describeMetadataQuorum(DescribeMetadataQuorumOptions)}
+ */
+public class DescribeMetadataQuorumOptions extends AbstractOptions<DescribeMetadataQuorumOptions> {
+
+}
diff --git a/clients/src/main/java/org/apache/kafka/clients/admin/DescribeMetadataQuorumResult.java b/clients/src/main/java/org/apache/kafka/clients/admin/DescribeMetadataQuorumResult.java
new file mode 100644
index 0000000000..aa9bbe84ea
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/clients/admin/DescribeMetadataQuorumResult.java
@@ -0,0 +1,38 @@
+/*
+ * 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.clients.admin;
+
+import org.apache.kafka.common.KafkaFuture;
+
+/**
+ * The result of {@link Admin#describeMetadataQuorum(DescribeMetadataQuorumOptions)}
+ */
+public class DescribeMetadataQuorumResult {
+
+ private final KafkaFuture<QuorumInfo> quorumInfo;
+
+ DescribeMetadataQuorumResult(KafkaFuture<QuorumInfo> quorumInfo) {
+ this.quorumInfo = quorumInfo;
+ }
+
+ /**
+ * Returns a future containing the QuorumInfo
+ */
+ public KafkaFuture<QuorumInfo> quorumInfo() {
+ return quorumInfo;
+ }
+}
diff --git a/clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java b/clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
index 613b0c3a9f..41a0a70240 100644
--- a/clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
+++ b/clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
@@ -135,6 +135,7 @@ import org.apache.kafka.common.message.DescribeConfigsResponseData;
import org.apache.kafka.common.message.DescribeLogDirsRequestData;
import org.apache.kafka.common.message.DescribeLogDirsRequestData.DescribableLogDirTopic;
import org.apache.kafka.common.message.DescribeLogDirsResponseData;
+import org.apache.kafka.common.message.DescribeQuorumResponseData;
import org.apache.kafka.common.message.DescribeUserScramCredentialsRequestData;
import org.apache.kafka.common.message.DescribeUserScramCredentialsRequestData.UserName;
import org.apache.kafka.common.message.DescribeUserScramCredentialsResponseData;
@@ -208,6 +209,9 @@ import org.apache.kafka.common.requests.DescribeLogDirsRequest;
import org.apache.kafka.common.requests.DescribeLogDirsResponse;
import org.apache.kafka.common.requests.DescribeUserScramCredentialsRequest;
import org.apache.kafka.common.requests.DescribeUserScramCredentialsResponse;
+import org.apache.kafka.common.requests.DescribeQuorumRequest;
+import org.apache.kafka.common.requests.DescribeQuorumRequest.Builder;
+import org.apache.kafka.common.requests.DescribeQuorumResponse;
import org.apache.kafka.common.requests.ElectLeadersRequest;
import org.apache.kafka.common.requests.ElectLeadersResponse;
import org.apache.kafka.common.requests.ExpireDelegationTokenRequest;
@@ -257,6 +261,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
+import java.util.OptionalLong;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
@@ -268,6 +273,8 @@ import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
+import static org.apache.kafka.common.internals.Topic.METADATA_TOPIC_NAME;
+import static org.apache.kafka.common.internals.Topic.METADATA_TOPIC_PARTITION;
import static org.apache.kafka.common.message.AlterPartitionReassignmentsRequestData.ReassignablePartition;
import static org.apache.kafka.common.message.AlterPartitionReassignmentsResponseData.ReassignablePartitionResponse;
import static org.apache.kafka.common.message.AlterPartitionReassignmentsResponseData.ReassignableTopicResponse;
@@ -4325,6 +4332,84 @@ public class KafkaAdminClient extends AdminClient {
return new UpdateFeaturesResult(new HashMap<>(updateFutures));
}
+ @Override
+ public DescribeMetadataQuorumResult describeMetadataQuorum(DescribeMetadataQuorumOptions options) {
+ NodeProvider provider = new LeastLoadedNodeProvider();
+
+ final KafkaFutureImpl<QuorumInfo> future = new KafkaFutureImpl<>();
+ final long now = time.milliseconds();
+ final Call call = new Call(
+ "describeMetadataQuorum", calcDeadlineMs(now, options.timeoutMs()), provider) {
+
+ private QuorumInfo.ReplicaState translateReplicaState(DescribeQuorumResponseData.ReplicaState replica) {
+ return new QuorumInfo.ReplicaState(
+ replica.replicaId(),
+ replica.logEndOffset(),
+ replica.lastFetchTimestamp() == -1 ? OptionalLong.empty() : OptionalLong.of(replica.lastFetchTimestamp()),
+ replica.lastCaughtUpTimestamp() == -1 ? OptionalLong.empty() : OptionalLong.of(replica.lastCaughtUpTimestamp()));
+ }
+
+ private QuorumInfo createQuorumResult(final DescribeQuorumResponseData.PartitionData partition) {
+ return new QuorumInfo(
+ partition.leaderId(),
+ partition.currentVoters().stream().map(v -> translateReplicaState(v)).collect(Collectors.toList()),
+ partition.observers().stream().map(o -> translateReplicaState(o)).collect(Collectors.toList()));
+ }
+
+ @Override
+ DescribeQuorumRequest.Builder createRequest(int timeoutMs) {
+ return new Builder(DescribeQuorumRequest.singletonRequest(
+ new TopicPartition(METADATA_TOPIC_NAME, METADATA_TOPIC_PARTITION.partition())));
+ }
+
+ @Override
+ void handleResponse(AbstractResponse response) {
+ final DescribeQuorumResponse quorumResponse = (DescribeQuorumResponse) response;
+ if (quorumResponse.data().errorCode() != Errors.NONE.code()) {
+ throw Errors.forCode(quorumResponse.data().errorCode()).exception();
+ }
+ if (quorumResponse.data().topics().size() != 1) {
+ String msg = String.format("DescribeMetadataQuorum received %d topics when 1 was expected",
+ quorumResponse.data().topics().size());
+ log.debug(msg);
+ throw new UnknownServerException(msg);
+ }
+ DescribeQuorumResponseData.TopicData topic = quorumResponse.data().topics().get(0);
+ if (!topic.topicName().equals(METADATA_TOPIC_NAME)) {
+ String msg = String.format("DescribeMetadataQuorum received a topic with name %s when %s was expected",
+ topic.topicName(), METADATA_TOPIC_NAME);
+ log.debug(msg);
+ throw new UnknownServerException(msg);
+ }
+ if (topic.partitions().size() != 1) {
+ String msg = String.format("DescribeMetadataQuorum received a topic %s with %d partitions when 1 was expected",
+ topic.topicName(), topic.partitions().size());
+ log.debug(msg);
+ throw new UnknownServerException(msg);
+ }
+ DescribeQuorumResponseData.PartitionData partition = topic.partitions().get(0);
+ if (partition.partitionIndex() != METADATA_TOPIC_PARTITION.partition()) {
+ String msg = String.format("DescribeMetadataQuorum received a single partition with index %d when %d was expected",
+ partition.partitionIndex(), METADATA_TOPIC_PARTITION.partition());
+ log.debug(msg);
+ throw new UnknownServerException(msg);
+ }
+ if (partition.errorCode() != Errors.NONE.code()) {
+ throw Errors.forCode(partition.errorCode()).exception();
+ }
+ future.complete(createQuorumResult(partition));
+ }
+
+ @Override
+ void handleFailure(Throwable throwable) {
+ future.completeExceptionally(throwable);
+ }
+ };
+
+ runnable.call(call, now);
+ return new DescribeMetadataQuorumResult(future);
+ }
+
@Override
public UnregisterBrokerResult unregisterBroker(int brokerId, UnregisterBrokerOptions options) {
final KafkaFutureImpl<Void> future = new KafkaFutureImpl<>();
diff --git a/clients/src/main/java/org/apache/kafka/clients/admin/QuorumInfo.java b/clients/src/main/java/org/apache/kafka/clients/admin/QuorumInfo.java
new file mode 100644
index 0000000000..75476d77dc
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/clients/admin/QuorumInfo.java
@@ -0,0 +1,153 @@
+/*
+ * 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.clients.admin;
+
+import java.util.List;
+import java.util.Objects;
+import java.util.OptionalLong;
+
+/**
+ * This class is used to describe the state of the quorum received in DescribeQuorumResponse.
+ */
+public class QuorumInfo {
+ private final Integer leaderId;
+ private final List<ReplicaState> voters;
+ private final List<ReplicaState> observers;
+
+ QuorumInfo(Integer leaderId, List<ReplicaState> voters, List<ReplicaState> observers) {
+ this.leaderId = leaderId;
+ this.voters = voters;
+ this.observers = observers;
+ }
+
+ public Integer leaderId() {
+ return leaderId;
+ }
+
+ public List<ReplicaState> voters() {
+ return voters;
+ }
+
+ public List<ReplicaState> observers() {
+ return observers;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ QuorumInfo that = (QuorumInfo) o;
+ return leaderId.equals(that.leaderId)
+ && voters.equals(that.voters)
+ && observers.equals(that.observers);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(leaderId, voters, observers);
+ }
+
+ @Override
+ public String toString() {
+ return "QuorumInfo(" +
+ "leaderId=" + leaderId +
+ ", voters=" + voters +
+ ", observers=" + observers +
+ ')';
+ }
+
+ public static class ReplicaState {
+ private final int replicaId;
+ private final long logEndOffset;
+ private final OptionalLong lastFetchTimeMs;
+ private final OptionalLong lastCaughtUpTimeMs;
+
+ ReplicaState() {
+ this(0, 0, OptionalLong.empty(), OptionalLong.empty());
+ }
+
+ ReplicaState(
+ int replicaId,
+ long logEndOffset,
+ OptionalLong lastFetchTimeMs,
+ OptionalLong lastCaughtUpTimeMs
+ ) {
+ this.replicaId = replicaId;
+ this.logEndOffset = logEndOffset;
+ this.lastFetchTimeMs = lastFetchTimeMs;
+ this.lastCaughtUpTimeMs = lastCaughtUpTimeMs;
+ }
+
+ /**
+ * Return the ID for this replica.
+ * @return The ID for this replica
+ */
+ public int replicaId() {
+ return replicaId;
+ }
+
+ /**
+ * Return the logEndOffset known by the leader for this replica.
+ * @return The logEndOffset for this replica
+ */
+ public long logEndOffset() {
+ return logEndOffset;
+ }
+
+ /**
+ * Return the lastFetchTime in milliseconds for this replica.
+ * @return The value of the lastFetchTime if known, empty otherwise
+ */
+ public OptionalLong lastFetchTimeMs() {
+ return lastFetchTimeMs;
+ }
+
+ /**
+ * Return the lastCaughtUpTime in milliseconds for this replica.
+ * @return The value of the lastCaughtUpTime if known, empty otherwise
+ */
+ public OptionalLong lastCaughtUpTimeMs() {
+ return lastCaughtUpTimeMs;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ ReplicaState that = (ReplicaState) o;
+ return replicaId == that.replicaId
+ && logEndOffset == that.logEndOffset
+ && lastFetchTimeMs.equals(that.lastFetchTimeMs)
+ && lastCaughtUpTimeMs.equals(that.lastCaughtUpTimeMs);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(replicaId, logEndOffset, lastFetchTimeMs, lastCaughtUpTimeMs);
+ }
+
+ @Override
+ public String toString() {
+ return "ReplicaState(" +
+ "replicaId=" + replicaId +
+ ", logEndOffset=" + logEndOffset +
+ ", lastFetchTimeMs=" + lastFetchTimeMs +
+ ", lastCaughtUpTimeMs=" + lastCaughtUpTimeMs +
+ ')';
+ }
+ }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/internals/Topic.java b/clients/src/main/java/org/apache/kafka/common/internals/Topic.java
index 3c93ef87b5..fbf491bab9 100644
--- a/clients/src/main/java/org/apache/kafka/common/internals/Topic.java
+++ b/clients/src/main/java/org/apache/kafka/common/internals/Topic.java
@@ -16,6 +16,7 @@
*/
package org.apache.kafka.common.internals;
+import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.InvalidTopicException;
import org.apache.kafka.common.utils.Utils;
@@ -27,6 +28,8 @@ public class Topic {
public static final String GROUP_METADATA_TOPIC_NAME = "__consumer_offsets";
public static final String TRANSACTION_STATE_TOPIC_NAME = "__transaction_state";
+ public static final String METADATA_TOPIC_NAME = "__cluster_metadata";
+ public static final TopicPartition METADATA_TOPIC_PARTITION = new TopicPartition(METADATA_TOPIC_NAME, 0);
public static final String LEGAL_CHARS = "[a-zA-Z0-9._-]";
private static final Set<String> INTERNAL_TOPICS = Collections.unmodifiableSet(
diff --git a/clients/src/main/resources/common/message/DescribeQuorumRequest.json b/clients/src/main/resources/common/message/DescribeQuorumRequest.json
index cd4a7f1db5..cee8fe6982 100644
--- a/clients/src/main/resources/common/message/DescribeQuorumRequest.json
+++ b/clients/src/main/resources/common/message/DescribeQuorumRequest.json
@@ -18,7 +18,8 @@
"type": "request",
"listeners": ["broker", "controller"],
"name": "DescribeQuorumRequest",
- "validVersions": "0",
+ // Version 1 adds additional fields in the response. The request is unchanged (KIP-836).
+ "validVersions": "0-1",
"flexibleVersions": "0+",
"fields": [
{ "name": "Topics", "type": "[]TopicData",
diff --git a/clients/src/main/resources/common/message/DescribeQuorumResponse.json b/clients/src/main/resources/common/message/DescribeQuorumResponse.json
index 444fee355a..0ea6271238 100644
--- a/clients/src/main/resources/common/message/DescribeQuorumResponse.json
+++ b/clients/src/main/resources/common/message/DescribeQuorumResponse.json
@@ -17,7 +17,8 @@
"apiKey": 55,
"type": "response",
"name": "DescribeQuorumResponse",
- "validVersions": "0",
+ // Version 1 adds LastFetchTimeStamp and LastCaughtUpTimestamp in ReplicaState (KIP-836).
+ "validVersions": "0-1",
"flexibleVersions": "0+",
"fields": [
{ "name": "ErrorCode", "type": "int16", "versions": "0+",
@@ -44,7 +45,11 @@
{ "name": "ReplicaState", "versions": "0+", "fields": [
{ "name": "ReplicaId", "type": "int32", "versions": "0+", "entityType": "brokerId" },
{ "name": "LogEndOffset", "type": "int64", "versions": "0+",
- "about": "The last known log end offset of the follower or -1 if it is unknown"}
+ "about": "The last known log end offset of the follower or -1 if it is unknown"},
+ { "name": "LastFetchTimestamp", "type": "int64", "versions": "1+", "ignorable": true, "default": -1,
+ "about": "The last known leader wall clock time time when a follower fetched from the leader. This is reported as -1 both for the current leader or if it is unknown for a voter"},
+ { "name": "LastCaughtUpTimestamp", "type": "int64", "versions": "1+", "ignorable": true, "default": -1,
+ "about": "The leader wall clock append time of the offset for which the follower made the most recent fetch request. This is reported as the current time for the leader and -1 if unknown for a voter"}
]}
]
}
diff --git a/clients/src/test/java/org/apache/kafka/clients/admin/KafkaAdminClientTest.java b/clients/src/test/java/org/apache/kafka/clients/admin/KafkaAdminClientTest.java
index 6eb936f5b4..b53c7cdb5f 100644
--- a/clients/src/test/java/org/apache/kafka/clients/admin/KafkaAdminClientTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/admin/KafkaAdminClientTest.java
@@ -69,6 +69,7 @@ import org.apache.kafka.common.errors.UnknownTopicIdException;
import org.apache.kafka.common.errors.UnknownTopicOrPartitionException;
import org.apache.kafka.common.errors.UnsupportedVersionException;
import org.apache.kafka.common.feature.Features;
+import org.apache.kafka.common.internals.Topic;
import org.apache.kafka.common.message.AlterPartitionReassignmentsResponseData;
import org.apache.kafka.common.message.AlterReplicaLogDirsResponseData;
import org.apache.kafka.common.message.AlterReplicaLogDirsResponseData.AlterReplicaLogDirPartitionResult;
@@ -100,6 +101,7 @@ import org.apache.kafka.common.message.DescribeGroupsResponseData.DescribedGroup
import org.apache.kafka.common.message.DescribeLogDirsResponseData;
import org.apache.kafka.common.message.DescribeLogDirsResponseData.DescribeLogDirsTopic;
import org.apache.kafka.common.message.DescribeProducersResponseData;
+import org.apache.kafka.common.message.DescribeQuorumResponseData;
import org.apache.kafka.common.message.DescribeTransactionsResponseData;
import org.apache.kafka.common.message.DescribeUserScramCredentialsResponseData;
import org.apache.kafka.common.message.DescribeUserScramCredentialsResponseData.CredentialInfo;
@@ -161,6 +163,8 @@ import org.apache.kafka.common.requests.DescribeGroupsResponse;
import org.apache.kafka.common.requests.DescribeLogDirsResponse;
import org.apache.kafka.common.requests.DescribeProducersRequest;
import org.apache.kafka.common.requests.DescribeProducersResponse;
+import org.apache.kafka.common.requests.DescribeQuorumRequest;
+import org.apache.kafka.common.requests.DescribeQuorumResponse;
import org.apache.kafka.common.requests.DescribeTransactionsRequest;
import org.apache.kafka.common.requests.DescribeTransactionsResponse;
import org.apache.kafka.common.requests.DescribeUserScramCredentialsResponse;
@@ -579,6 +583,48 @@ public class KafkaAdminClientTest {
.setErrorCode(error.code()));
}
+ private static QuorumInfo defaultQuorumInfo(Boolean emptyOptionals) {
+ return new QuorumInfo(1,
+ singletonList(new QuorumInfo.ReplicaState(1, 100,
+ emptyOptionals ? OptionalLong.empty() : OptionalLong.of(1000),
+ emptyOptionals ? OptionalLong.empty() : OptionalLong.of(1000))),
+ singletonList(new QuorumInfo.ReplicaState(1, 100,
+ emptyOptionals ? OptionalLong.empty() : OptionalLong.of(1000),
+ emptyOptionals ? OptionalLong.empty() : OptionalLong.of(1000))));
+ }
+
+ private static DescribeQuorumResponse prepareDescribeQuorumResponse(
+ Errors topLevelError,
+ Errors partitionLevelError,
+ Boolean topicCountError,
+ Boolean topicNameError,
+ Boolean partitionCountError,
+ Boolean partitionIndexError,
+ Boolean emptyOptionals) {
+ String topicName = topicNameError ? "RANDOM" : Topic.METADATA_TOPIC_NAME;
+ Integer partitionIndex = partitionIndexError ? 1 : Topic.METADATA_TOPIC_PARTITION.partition();
+ List<DescribeQuorumResponseData.TopicData> topics = new ArrayList<>();
+ List<DescribeQuorumResponseData.PartitionData> partitions = new ArrayList<>();
+ for (int i = 0; i < (partitionCountError ? 2 : 1); i++) {
+ DescribeQuorumResponseData.ReplicaState replica = new DescribeQuorumResponseData.ReplicaState()
+ .setReplicaId(1)
+ .setLogEndOffset(100);
+ replica.setLastFetchTimestamp(emptyOptionals ? -1 : 1000);
+ replica.setLastCaughtUpTimestamp(emptyOptionals ? -1 : 1000);
+ partitions.add(new DescribeQuorumResponseData.PartitionData().setPartitionIndex(partitionIndex)
+ .setLeaderId(1)
+ .setLeaderEpoch(0)
+ .setHighWatermark(0)
+ .setCurrentVoters(singletonList(replica))
+ .setObservers(singletonList(replica))
+ .setErrorCode(partitionLevelError.code()));
+ }
+ for (int i = 0; i < (topicCountError ? 2 : 1); i++) {
+ topics.add(new DescribeQuorumResponseData.TopicData().setTopicName(topicName).setPartitions(partitions));
+ }
+ return new DescribeQuorumResponse(new DescribeQuorumResponseData().setTopics(topics).setErrorCode(topLevelError.code()));
+ }
+
/**
* Test that the client properly times out when we don't receive any metadata.
*/
@@ -4903,6 +4949,96 @@ public class KafkaAdminClientTest {
}
}
+ @Test
+ public void testDescribeMetadataQuorumSuccess() throws Exception {
+ try (final AdminClientUnitTestEnv env = mockClientEnv()) {
+ env.kafkaClient().setNodeApiVersions(NodeApiVersions.create(ApiKeys.DESCRIBE_QUORUM.id,
+ ApiKeys.DESCRIBE_QUORUM.oldestVersion(),
+ ApiKeys.DESCRIBE_QUORUM.latestVersion()));
+
+ // Test with optional fields set
+ env.kafkaClient().prepareResponse(
+ body -> body instanceof DescribeQuorumRequest,
+ prepareDescribeQuorumResponse(Errors.NONE, Errors.NONE, false, false, false, false, false));
+ KafkaFuture<QuorumInfo> future = env.adminClient().describeMetadataQuorum().quorumInfo();
+ QuorumInfo quorumInfo = future.get();
+ assertEquals(defaultQuorumInfo(false), quorumInfo);
+
+ // Test with optional fields empty
+ env.kafkaClient().prepareResponse(
+ body -> body instanceof DescribeQuorumRequest,
+ prepareDescribeQuorumResponse(Errors.NONE, Errors.NONE, false, false, false, false, true));
+ future = env.adminClient().describeMetadataQuorum().quorumInfo();
+ quorumInfo = future.get();
+ assertEquals(defaultQuorumInfo(true), quorumInfo);
+ }
+ }
+
+ @Test
+ public void testDescribeMetadataQuorumFailure() {
+ try (final AdminClientUnitTestEnv env = mockClientEnv()) {
+ env.kafkaClient().setNodeApiVersions(NodeApiVersions.create(ApiKeys.DESCRIBE_QUORUM.id,
+ ApiKeys.DESCRIBE_QUORUM.oldestVersion(),
+ ApiKeys.DESCRIBE_QUORUM.latestVersion()));
+
+ // Test top level error
+ env.kafkaClient().prepareResponse(
+ body -> body instanceof DescribeQuorumRequest,
+ prepareDescribeQuorumResponse(Errors.INVALID_REQUEST, Errors.NONE, false, false, false, false, false));
+ KafkaFuture<QuorumInfo> future = env.adminClient().describeMetadataQuorum().quorumInfo();
+ TestUtils.assertFutureThrows(future, InvalidRequestException.class);
+
+ // Test incorrect topic count
+ env.kafkaClient().prepareResponse(
+ body -> body instanceof DescribeQuorumRequest,
+ prepareDescribeQuorumResponse(Errors.NONE, Errors.NONE, true, false, false, false, false));
+ future = env.adminClient().describeMetadataQuorum().quorumInfo();
+ TestUtils.assertFutureThrows(future, UnknownServerException.class);
+
+ // Test incorrect topic name
+ env.kafkaClient().prepareResponse(
+ body -> body instanceof DescribeQuorumRequest,
+ prepareDescribeQuorumResponse(Errors.NONE, Errors.NONE, false, true, false, false, false));
+ future = env.adminClient().describeMetadataQuorum().quorumInfo();
+ TestUtils.assertFutureThrows(future, UnknownServerException.class);
+
+ // Test incorrect partition count
+ env.kafkaClient().prepareResponse(
+ body -> body instanceof DescribeQuorumRequest,
+ prepareDescribeQuorumResponse(Errors.NONE, Errors.NONE, false, false, true, false, false));
+ future = env.adminClient().describeMetadataQuorum().quorumInfo();
+ TestUtils.assertFutureThrows(future, UnknownServerException.class);
+
+ // Test incorrect partition index
+ env.kafkaClient().prepareResponse(
+ body -> body instanceof DescribeQuorumRequest,
+ prepareDescribeQuorumResponse(Errors.NONE, Errors.NONE, false, false, false, true, false));
+ future = env.adminClient().describeMetadataQuorum().quorumInfo();
+ TestUtils.assertFutureThrows(future, UnknownServerException.class);
+
+ // Test partition level error
+ env.kafkaClient().prepareResponse(
+ body -> body instanceof DescribeQuorumRequest,
+ prepareDescribeQuorumResponse(Errors.NONE, Errors.INVALID_REQUEST, false, false, false, false, false));
+ future = env.adminClient().describeMetadataQuorum().quorumInfo();
+ TestUtils.assertFutureThrows(future, InvalidRequestException.class);
+
+ // Test all incorrect and no errors
+ env.kafkaClient().prepareResponse(
+ body -> body instanceof DescribeQuorumRequest,
+ prepareDescribeQuorumResponse(Errors.NONE, Errors.NONE, true, true, true, true, false));
+ future = env.adminClient().describeMetadataQuorum().quorumInfo();
+ TestUtils.assertFutureThrows(future, UnknownServerException.class);
+
+ // Test all incorrect and both errors
+ env.kafkaClient().prepareResponse(
+ body -> body instanceof DescribeQuorumRequest,
+ prepareDescribeQuorumResponse(Errors.INVALID_REQUEST, Errors.INVALID_REQUEST, true, true, true, true, false));
+ future = env.adminClient().describeMetadataQuorum().quorumInfo();
+ TestUtils.assertFutureThrows(future, Errors.INVALID_REQUEST.exception().getClass());
+ }
+ }
+
@Test
public void testListOffsetsMetadataRetriableErrors() throws Exception {
diff --git a/clients/src/test/java/org/apache/kafka/clients/admin/MockAdminClient.java b/clients/src/test/java/org/apache/kafka/clients/admin/MockAdminClient.java
index 15cdc5ccc4..7bac8803fe 100644
--- a/clients/src/test/java/org/apache/kafka/clients/admin/MockAdminClient.java
+++ b/clients/src/test/java/org/apache/kafka/clients/admin/MockAdminClient.java
@@ -962,6 +962,11 @@ public class MockAdminClient extends AdminClient {
throw new UnsupportedOperationException("Not implemented yet");
}
+ @Override
+ public DescribeMetadataQuorumResult describeMetadataQuorum(DescribeMetadataQuorumOptions options) {
+ throw new UnsupportedOperationException("Not implemented yet");
+ }
+
@Override
public DescribeFeaturesResult describeFeatures(DescribeFeaturesOptions options) {
throw new UnsupportedOperationException("Not implemented yet");
diff --git a/core/src/main/scala/kafka/server/KafkaRaftServer.scala b/core/src/main/scala/kafka/server/KafkaRaftServer.scala
index f1474430b9..07a3118372 100644
--- a/core/src/main/scala/kafka/server/KafkaRaftServer.scala
+++ b/core/src/main/scala/kafka/server/KafkaRaftServer.scala
@@ -25,8 +25,9 @@ import kafka.raft.KafkaRaftManager
import kafka.server.KafkaRaftServer.{BrokerRole, ControllerRole}
import kafka.utils.{CoreUtils, Logging, Mx4jLoader, VerifiableProperties}
import org.apache.kafka.common.config.{ConfigDef, ConfigResource}
+import org.apache.kafka.common.internals.Topic
import org.apache.kafka.common.utils.{AppInfoParser, Time}
-import org.apache.kafka.common.{KafkaException, TopicPartition, Uuid}
+import org.apache.kafka.common.{KafkaException, Uuid}
import org.apache.kafka.controller.BootstrapMetadata
import org.apache.kafka.metadata.{KafkaConfigSchema, MetadataRecordSerde}
import org.apache.kafka.raft.RaftConfig
@@ -136,8 +137,8 @@ class KafkaRaftServer(
}
object KafkaRaftServer {
- val MetadataTopic = "__cluster_metadata"
- val MetadataPartition = new TopicPartition(MetadataTopic, 0)
+ val MetadataTopic = Topic.METADATA_TOPIC_NAME
+ val MetadataPartition = Topic.METADATA_TOPIC_PARTITION
val MetadataTopicId = Uuid.METADATA_TOPIC_ID
sealed trait ProcessRole
diff --git a/core/src/test/scala/unit/kafka/server/DescribeQuorumRequestTest.scala b/core/src/test/scala/unit/kafka/server/DescribeQuorumRequestTest.scala
index 55b9fe92c3..f8da00f10e 100644
--- a/core/src/test/scala/unit/kafka/server/DescribeQuorumRequestTest.scala
+++ b/core/src/test/scala/unit/kafka/server/DescribeQuorumRequestTest.scala
@@ -17,7 +17,6 @@
package kafka.server
import java.io.IOException
-
import kafka.test.ClusterInstance
import kafka.test.annotation.{ClusterTest, ClusterTestDefaults, Type}
import kafka.test.junit.ClusterTestExtensions
@@ -26,12 +25,13 @@ import org.apache.kafka.common.protocol.{ApiKeys, Errors}
import org.apache.kafka.common.requests.DescribeQuorumRequest.singletonRequest
import org.apache.kafka.common.requests.{AbstractRequest, AbstractResponse, ApiVersionsRequest, ApiVersionsResponse, DescribeQuorumRequest, DescribeQuorumResponse}
import org.junit.jupiter.api.Assertions._
-import org.junit.jupiter.api.Tag
+import org.junit.jupiter.api.{Tag, Timeout}
import org.junit.jupiter.api.extension.ExtendWith
import scala.jdk.CollectionConverters._
import scala.reflect.ClassTag
+@Timeout(120)
@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
@ClusterTestDefaults(clusterType = Type.KRAFT)
@Tag("integration")
@@ -54,30 +54,42 @@ class DescribeQuorumRequestTest(cluster: ClusterInstance) {
@ClusterTest
def testDescribeQuorum(): Unit = {
- val request = new DescribeQuorumRequest.Builder(
- singletonRequest(KafkaRaftServer.MetadataPartition)
- ).build()
-
- val response = connectAndReceive[DescribeQuorumResponse](request)
-
- assertEquals(Errors.NONE, Errors.forCode(response.data.errorCode))
- assertEquals(1, response.data.topics.size)
-
- val topicData = response.data.topics.get(0)
- assertEquals(KafkaRaftServer.MetadataTopic, topicData.topicName)
- assertEquals(1, topicData.partitions.size)
-
- val partitionData = topicData.partitions.get(0)
- assertEquals(KafkaRaftServer.MetadataPartition.partition, partitionData.partitionIndex)
- assertEquals(Errors.NONE, Errors.forCode(partitionData.errorCode))
- assertTrue(partitionData.leaderEpoch > 0)
-
- val leaderId = partitionData.leaderId
- assertTrue(leaderId > 0)
-
- val leaderState = partitionData.currentVoters.asScala.find(_.replicaId == leaderId)
- .getOrElse(throw new AssertionError("Failed to find leader among current voter states"))
- assertTrue(leaderState.logEndOffset > 0)
+ for (version <- ApiKeys.DESCRIBE_QUORUM.allVersions.asScala) {
+ val request = new DescribeQuorumRequest.Builder(
+ singletonRequest(KafkaRaftServer.MetadataPartition)
+ ).build(version.toShort)
+ val response = connectAndReceive[DescribeQuorumResponse](request)
+
+ assertEquals(Errors.NONE, Errors.forCode(response.data.errorCode))
+ assertEquals(1, response.data.topics.size)
+
+ val topicData = response.data.topics.get(0)
+ assertEquals(KafkaRaftServer.MetadataTopic, topicData.topicName)
+ assertEquals(1, topicData.partitions.size)
+
+ val partitionData = topicData.partitions.get(0)
+ assertEquals(KafkaRaftServer.MetadataPartition.partition, partitionData.partitionIndex)
+ assertEquals(Errors.NONE, Errors.forCode(partitionData.errorCode))
+ assertTrue(partitionData.leaderEpoch > 0)
+
+ val leaderId = partitionData.leaderId
+ assertTrue(leaderId > 0)
+
+ val leaderState = partitionData.currentVoters.asScala.find(_.replicaId == leaderId)
+ .getOrElse(throw new AssertionError("Failed to find leader among current voter states"))
+ assertTrue(leaderState.logEndOffset > 0)
+
+ val voterData = partitionData.currentVoters.asScala
+ val observerData = partitionData.observers.asScala
+ assertEquals(1, voterData.size)
+ assertEquals(0, observerData.size)
+ voterData.foreach { state =>
+ assertTrue(0 < state.replicaId)
+ assertTrue(0 < state.logEndOffset)
+ assertEquals(-1, state.lastFetchTimestamp)
+ assertEquals(-1, state.lastCaughtUpTimestamp)
+ }
+ }
}
private def connectAndReceive[T <: AbstractResponse](