You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by GitBox <gi...@apache.org> on 2021/06/26 00:59:43 UTC
[GitHub] [kafka] cmccabe opened a new pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
cmccabe opened a new pull request #10931:
URL: https://github.com/apache/kafka/pull/10931
This PR implements broker-side KRaft snapshots, including both saving and
loading. The code for triggering a periodic broker-side snapshot will come in a
follow-on PR. Loading should work with just this PR. It also implements
reloading broker snapshots after initialization.
In order to facilitate snapshots, this PR introduces the concept of
MetadataImage and MetadataDelta. MetadataImage represents the metadata state
retained in memory. It is basically a generalization of MetadataCache that
includes a few things that MetadataCache does not (such as features and client
quotas.) KRaftMetadataCache is now an accessor for the data stored in this object.
Similarly, MetadataImage replaces CacheConfigRespository and ClientQuotaCache.
It also subsumes kafka.server.metadata.MetadataImage and related classes.
MetadataDelta represents a change to a MetadataImage. When a KRaft snapshot is
loaded, we will accumulate all the changes into a MetadataDelta first, prior to
applying it. If we must reload a snapshot because we fell too far behind while
consuming metadata, the resulting MetadataDelta will contain all the changes
needed to catch us up. During normal operation, MetadataDelta is also used to
accumulate the changes of each incoming batch of metadata records. These
incremental deltas should be relatively small.
I have removed the logic for updating the various manager objects from
BrokerMetadataListener and placed it into BrokerMetadataPublisher. This makes
it easier to unit test BrokerMetadataListener.
This is a work in progress ... I need to add some more tests
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r661665310
##########
File path: metadata/src/main/java/org/apache/kafka/image/ClientQuotasImage.java
##########
@@ -0,0 +1,178 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.message.DescribeClientQuotasRequestData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData.EntityData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData.EntryData;
+import org.apache.kafka.common.quota.ClientQuotaEntity;
+import org.apache.kafka.server.common.ApiMessageAndVersion;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.common.protocol.Errors.INVALID_REQUEST;
+import static org.apache.kafka.common.protocol.Errors.UNSUPPORTED_VERSION;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_EXACT;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_DEFAULT;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_SPECIFIED;
+
+
+/**
+ * Represents the client quotas in the metadata image.
+ *
+ * This class is thread-safe.
+ */
+public final class ClientQuotasImage {
+ public final static ClientQuotasImage EMPTY = new ClientQuotasImage(Collections.emptyMap());
+
+ private final Map<ClientQuotaEntity, ClientQuotaImage> entities;
+
+ public ClientQuotasImage(Map<ClientQuotaEntity, ClientQuotaImage> entities) {
+ this.entities = entities;
+ }
+
+ public boolean isEmpty() {
+ return entities.isEmpty();
+ }
+
+ Map<ClientQuotaEntity, ClientQuotaImage> entities() {
+ return entities;
+ }
+
+ public void write(Consumer<List<ApiMessageAndVersion>> out) throws IOException {
+ for (Entry<ClientQuotaEntity, ClientQuotaImage> entry : entities.entrySet()) {
+ ClientQuotaEntity entity = entry.getKey();
+ ClientQuotaImage clientQuotaImage = entry.getValue();
+ clientQuotaImage.write(entity, out);
+ }
+ }
+
+ public DescribeClientQuotasResponseData describe(DescribeClientQuotasRequestData request) {
+ DescribeClientQuotasResponseData response = new DescribeClientQuotasResponseData();
+ Map<String, String> exact = new HashMap<>();
+ Set<String> any = new HashSet<>();
Review comment:
OK
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663430447
##########
File path: core/src/main/scala/kafka/server/ReplicaManager.scala
##########
@@ -2011,7 +2011,16 @@ class ReplicaManager(val config: KafkaConfig,
"directory.")
None
- case HostedPartition.Online(partition) => Some(partition, false)
+ case HostedPartition.Online(partition) => {
+ if (partition.topicId.isDefined && !partition.topicId.equals(topicId)) {
Review comment:
good catch
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r660743774
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
No worries. Thanks for taking 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.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r661675478
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
Take a look at the code in `raft/`, which handles storing and replaying the log
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r661666247
##########
File path: metadata/src/main/java/org/apache/kafka/image/ClientQuotasImage.java
##########
@@ -0,0 +1,178 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.message.DescribeClientQuotasRequestData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData.EntityData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData.EntryData;
+import org.apache.kafka.common.quota.ClientQuotaEntity;
+import org.apache.kafka.server.common.ApiMessageAndVersion;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.common.protocol.Errors.INVALID_REQUEST;
+import static org.apache.kafka.common.protocol.Errors.UNSUPPORTED_VERSION;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_EXACT;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_DEFAULT;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_SPECIFIED;
+
+
+/**
+ * Represents the client quotas in the metadata image.
+ *
+ * This class is thread-safe.
+ */
+public final class ClientQuotasImage {
+ public final static ClientQuotasImage EMPTY = new ClientQuotasImage(Collections.emptyMap());
+
+ private final Map<ClientQuotaEntity, ClientQuotaImage> entities;
+
+ public ClientQuotasImage(Map<ClientQuotaEntity, ClientQuotaImage> entities) {
+ this.entities = entities;
+ }
+
+ public boolean isEmpty() {
+ return entities.isEmpty();
+ }
+
+ Map<ClientQuotaEntity, ClientQuotaImage> entities() {
+ return entities;
+ }
+
+ public void write(Consumer<List<ApiMessageAndVersion>> out) throws IOException {
+ for (Entry<ClientQuotaEntity, ClientQuotaImage> entry : entities.entrySet()) {
+ ClientQuotaEntity entity = entry.getKey();
+ ClientQuotaImage clientQuotaImage = entry.getValue();
+ clientQuotaImage.write(entity, out);
+ }
+ }
+
+ public DescribeClientQuotasResponseData describe(DescribeClientQuotasRequestData request) {
+ DescribeClientQuotasResponseData response = new DescribeClientQuotasResponseData();
+ Map<String, String> exact = new HashMap<>();
+ Set<String> any = new HashSet<>();
+ for (DescribeClientQuotasRequestData.ComponentData component : request.components()) {
+ switch (component.matchType()) {
+ case MATCH_TYPE_EXACT:
+ if (component.match() == null) {
+ response.setErrorCode(INVALID_REQUEST.code());
+ response.setErrorMessage("Request specified MATCH_TYPE_EXACT, " +
+ "but set match string to null.");
+ return response;
+ }
+ exact.put(component.entityType(), component.match());
+ break;
+ case MATCH_TYPE_DEFAULT:
+ if (component.match() != null) {
+ response.setErrorCode(INVALID_REQUEST.code());
+ response.setErrorMessage("Request specified MATCH_TYPE_DEFAULT, " +
+ "but also specified a match string.");
+ return response;
+ }
+ exact.put(component.entityType(), null);
+ break;
+ case MATCH_TYPE_SPECIFIED:
+ if (component.match() != null) {
+ response.setErrorCode(INVALID_REQUEST.code());
+ response.setErrorMessage("Request specified MATCH_TYPE_SPECIFIED, " +
+ "but also specified a match string.");
+ return response;
+ }
+ any.add(component.entityType());
+ break;
+ default:
+ response.setErrorCode(UNSUPPORTED_VERSION.code());
+ response.setErrorMessage("Unknown match type " + component.matchType());
+ return response;
+ }
+ }
+ // TODO: this is O(N). We should do some indexing here to speed it up.
Review comment:
This replaces the cache in `ClientQuotaCache`. I do think we should eventually do something fancier here (like have multiple maps, etc.)
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663275737
##########
File path: core/src/main/scala/kafka/server/ReplicaManager.scala
##########
@@ -2032,4 +2001,207 @@ class ReplicaManager(val config: KafkaConfig,
}
}
+ private[kafka] def getOrCreatePartition(tp: TopicPartition,
+ delta: TopicsDelta,
+ topicId: Uuid): Option[(Partition, Boolean)] = {
+ getPartition(tp) match {
+ case HostedPartition.Offline =>
+ stateChangeLogger.warn(s"Unable to bring up new local leader ${tp} " +
+ s"with topic id ${topicId} because it resides in an offline log " +
+ "directory.")
+ None
+
+ case HostedPartition.Online(partition) => Some(partition, false)
+
+ case HostedPartition.None =>
+ if (delta.image().topicsById().containsKey(topicId)) {
+ stateChangeLogger.error(s"Expected partition ${tp} with topic id " +
+ s"${topicId} to exist, but it was missing. Creating...")
+ } else {
+ stateChangeLogger.info(s"Creating new partition ${tp} with topic id " +
+ s"${topicId}.")
+ }
+ // it's a partition that we don't know about yet, so create it and mark it online
+ val partition = Partition(tp, time, this)
+ allPartitions.put(tp, HostedPartition.Online(partition))
+ Some(partition, true)
+ }
+ }
+
+ private[kafka] def calculateDeltaChanges(delta: TopicsDelta)
+ : (mutable.HashMap[TopicPartition, Boolean],
+ mutable.HashMap[TopicPartition, LocalLeaderInfo],
+ mutable.HashMap[TopicPartition, LocalLeaderInfo]) = {
+ val deleted = new mutable.HashMap[TopicPartition, Boolean]()
+ delta.deletedTopicIds().forEach { topicId =>
+ val topicImage = delta.image().getTopic(topicId)
+ topicImage.partitions().keySet().forEach { partitionId =>
+ deleted.put(new TopicPartition(topicImage.name(), partitionId), true)
+ }
+ }
+ val newLocalLeaders = new mutable.HashMap[TopicPartition, LocalLeaderInfo]()
+ val newLocalFollowers = new mutable.HashMap[TopicPartition, LocalLeaderInfo]()
+ delta.changedTopics().values().forEach { topicDelta =>
+ topicDelta.newLocalLeaders(config.nodeId).forEach { e =>
+ newLocalLeaders.put(new TopicPartition(topicDelta.name(), e.getKey),
+ LocalLeaderInfo(topicDelta.id(), e.getValue))
+ }
+ topicDelta.newLocalFollowers(config.nodeId).forEach { e =>
+ newLocalFollowers.put(new TopicPartition(topicDelta.name(), e.getKey),
+ LocalLeaderInfo(topicDelta.id(), e.getValue))
+ }
+ }
+ (deleted, newLocalLeaders, newLocalFollowers)
+ }
+
+ /**
+ * Apply a KRaft topic change delta.
+ *
+ * @param newImage The new metadata image.
+ * @param delta The delta to apply.
+ */
+ def applyDelta(newImage: MetadataImage, delta: TopicsDelta): Unit = {
+ // Before taking the lock, build some hash maps that we will need.
+ val (deleted, newLocalLeaders, newLocalFollowers) = calculateDeltaChanges(delta)
+
+ replicaStateChangeLock.synchronized {
+ // Handle deleted partitions. We need to do this first because we might subsequently
+ // create new partitions with the same names as the ones we are deleting here.
+ if (!deleted.isEmpty) {
+ stateChangeLogger.info(s"Deleting ${deleted.size} partition(s).")
+ stopPartitions(deleted).foreach { case (topicPartition, e) =>
+ if (e.isInstanceOf[KafkaStorageException]) {
+ stateChangeLogger.error(s"Unable to delete replica ${topicPartition} because " +
+ "the local replica for the partition is in an offline log directory")
+ } else {
+ stateChangeLogger.error(s"Unable to delete replica ${topicPartition} because " +
+ s"we got an unexpected ${e.getClass.getName} exception: ${e.getMessage}")
+ }
+ }
+ }
+ // Handle partitions which we are now the leader or follower for.
+ if (!newLocalLeaders.isEmpty || !newLocalFollowers.isEmpty) {
+ val lazyOffsetCheckpoints = new LazyOffsetCheckpoints(this.highWatermarkCheckpoints)
+ val changedPartitions = new mutable.HashSet[Partition]
+ if (!newLocalLeaders.isEmpty) {
+ applyLocalLeadersDelta(changedPartitions, delta, lazyOffsetCheckpoints, newLocalLeaders)
+ }
+ if (!newLocalFollowers.isEmpty) {
+ applyLocalFollowersDelta(changedPartitions, newImage, delta, lazyOffsetCheckpoints, newLocalFollowers)
+ }
+ maybeAddLogDirFetchers(changedPartitions, lazyOffsetCheckpoints,
+ name => Option(newImage.topics().getTopic(name)).map(_.id()))
+
+ def markPartitionOfflineIfNeeded(tp: TopicPartition): Unit = {
+ /*
+ * If there is offline log directory, a Partition object may have been created by getOrCreatePartition()
+ * before getOrCreateReplica() failed to create local replica due to KafkaStorageException.
+ * In this case ReplicaManager.allPartitions will map this topic-partition to an empty Partition object.
+ * we need to map this topic-partition to OfflinePartition instead.
+ */
+ if (localLog(tp).isEmpty)
+ markPartitionOffline(tp)
+ }
+ newLocalLeaders.keySet.foreach(markPartitionOfflineIfNeeded(_))
+ newLocalFollowers.keySet.foreach(markPartitionOfflineIfNeeded(_))
+
+ replicaFetcherManager.shutdownIdleFetcherThreads()
+ replicaAlterLogDirsManager.shutdownIdleFetcherThreads()
+ }
+ }
+ }
+
+ private def applyLocalLeadersDelta(changedPartitions: mutable.HashSet[Partition],
+ delta: TopicsDelta,
+ offsetCheckpoints: OffsetCheckpoints,
+ newLocalLeaders: mutable.HashMap[TopicPartition, LocalLeaderInfo]): Unit = {
+ stateChangeLogger.info(s"Transitioning ${newLocalLeaders.size} partition(s) to " +
+ "local leaders.")
+ replicaFetcherManager.removeFetcherForPartitions(newLocalLeaders.keySet)
+ newLocalLeaders.forKeyValue { case (tp, info) =>
+ getOrCreatePartition(tp, delta, info.topicId).foreach { case (partition, isNew) =>
+ try {
+ val state = info.partition.toLeaderAndIsrPartitionState(tp, isNew)
+ if (!partition.makeLeader(state, offsetCheckpoints, Some(info.topicId))) {
+ stateChangeLogger.info("Skipped the become-leader state change for " +
+ s"${tp} with topic id ${info.topicId} because this partition is " +
+ "already a local leader.")
+ }
+ changedPartitions.add(partition)
+ } catch {
+ case e: KafkaStorageException =>
+ stateChangeLogger.info(s"Skipped the become-leader state change for ${tp} " +
+ s"with topic id ${info.topicId} due to disk error ${e}")
+ val dirOpt = getLogDir(tp)
+ error(s"Error while making broker the leader for partition ${tp} in dir " +
+ s"${dirOpt}", e)
+ }
+ }
+ }
+ }
+
+ private def applyLocalFollowersDelta(changedPartitions: mutable.HashSet[Partition],
+ newImage: MetadataImage,
+ delta: TopicsDelta,
+ offsetCheckpoints: OffsetCheckpoints,
+ newLocalFollowers: mutable.HashMap[TopicPartition, LocalLeaderInfo]): Unit = {
+ stateChangeLogger.info(s"Transitioning ${newLocalFollowers.size} partition(s) to " +
+ "local followers.")
+ replicaFetcherManager.removeFetcherForPartitions(newLocalFollowers.keySet)
+ val shuttingDown = isShuttingDown.get()
+ val partitionsToMakeFollower = new mutable.HashMap[TopicPartition, InitialFetchState]
+ val newFollowerTopicSet = new mutable.HashSet[String]
+ newLocalFollowers.forKeyValue { case (tp, info) =>
+ getOrCreatePartition(tp, delta, info.topicId).foreach { case (partition, isNew) =>
+ try {
+ newFollowerTopicSet.add(tp.topic())
+
+ completeDelayedFetchOrProduceRequests(tp)
+
+ // Create the local replica even if the leader is unavailable. This is required
+ // to ensure that we include the partition's high watermark in the checkpoint
+ // file (see KAFKA-1647)
+ partition.createLogIfNotExists(isNew, false, offsetCheckpoints, Some(info.topicId))
+
+ if (shuttingDown) {
+ stateChangeLogger.trace(s"Unable to start fetching ${tp} with topic " +
+ s"ID ${info.topicId} because the replica manager is shutting down.")
+ } else {
+ val listenerName = config.interBrokerListenerName.value()
+ val leader = info.partition.leader
+ Option(newImage.cluster().broker(leader)).flatMap(_.node(listenerName).asScala) match {
+ case None => stateChangeLogger.trace(s"Unable to start fetching ${tp} " +
+ s"with topic ID ${info.topicId} from leader ${leader} because it is not " +
+ "alive.")
+ case Some(node) =>
+ val leaderEndPoint = new BrokerEndPoint(node.id(), node.host(), node.port())
+ val log = partition.localLogOrException
+ val fetchOffset = initialFetchOffset(log)
+ partitionsToMakeFollower.put(tp,
+ InitialFetchState(leaderEndPoint, partition.getLeaderEpoch, fetchOffset))
+ }
+ }
+ changedPartitions.add(partition)
+ } catch {
+ case e: Throwable => stateChangeLogger.error(s"Unable to start fetching ${tp} " +
Review comment:
Seems reasonable. It does say the partitions that had "unexpected errors" should end up there.
I'll add 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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r659940260
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
If the topic is created and then deleted within the same delta, the topic log dir is never created, so there is no need for it to be deleted.
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r661674972
##########
File path: core/src/main/scala/kafka/server/metadata/BrokerMetadataListener.scala
##########
@@ -70,230 +58,191 @@ class BrokerMetadataListener(
*/
@volatile private var _highestMetadataOffset = -1L
+ /**
+ * The current broker metadata image. Accessed only from the event queue thread.
+ */
+ private var _image = MetadataImage.EMPTY
+
+ /**
+ * The current metadata delta. Accessed only from the event queue thread.
+ */
+ private var _delta = new MetadataDelta(_image)
+
+ /**
+ * The object to use to publish new metadata changes, or None if this listener has not
+ * been activated yet.
+ */
+ private var _publisher: Option[MetadataPublisher] = None
+
+ /**
+ * The event queue which runs this listener.
+ */
val eventQueue = new KafkaEventQueue(time, logContext, threadNamePrefix.getOrElse(""))
+ /**
+ * Returns the highest metadata-offset. Thread-safe.
+ */
def highestMetadataOffset(): Long = _highestMetadataOffset
/**
* Handle new metadata records.
*/
- override def handleCommit(reader: BatchReader[ApiMessageAndVersion]): Unit = {
+ override def handleCommit(reader: BatchReader[ApiMessageAndVersion]): Unit =
eventQueue.append(new HandleCommitsEvent(reader))
+
+ class HandleCommitsEvent(reader: BatchReader[ApiMessageAndVersion])
+ extends EventQueue.FailureLoggingEvent(log) {
+ override def run(): Unit = {
+ val results = try {
+ val loadResults = loadBatches(_delta, reader)
+ if (isDebugEnabled) {
+ debug(s"Loaded new commits: ${loadResults}")
+ }
+ loadResults
+ } finally {
+ reader.close()
+ }
+ maybePublish(results.highestMetadataOffset)
+ }
}
/**
* Handle metadata snapshots
*/
- override def handleSnapshot(reader: SnapshotReader[ApiMessageAndVersion]): Unit = {
- // Loading snapshot on the broker is currently not supported.
- reader.close();
- throw new UnsupportedOperationException(s"Loading snapshot (${reader.snapshotId()}) is not supported")
- }
-
- // Visible for testing. It's useful to execute events synchronously in order
- // to make tests deterministic. This object is responsible for closing the reader.
- private[metadata] def execCommits(batchReader: BatchReader[ApiMessageAndVersion]): Unit = {
- new HandleCommitsEvent(batchReader).run()
- }
+ override def handleSnapshot(reader: SnapshotReader[ApiMessageAndVersion]): Unit =
+ eventQueue.append(new HandleSnapshotEvent(reader))
- class HandleCommitsEvent(
- reader: BatchReader[ApiMessageAndVersion]
- ) extends EventQueue.FailureLoggingEvent(log) {
+ class HandleSnapshotEvent(reader: SnapshotReader[ApiMessageAndVersion])
+ extends EventQueue.FailureLoggingEvent(log) {
override def run(): Unit = {
- try {
- while (reader.hasNext()) {
- apply(reader.next())
- }
+ val results = try {
+ info(s"Loading snapshot ${reader.snapshotId().offset}-${reader.snapshotId().epoch}.")
+ _delta = new MetadataDelta(_image) // Discard any previous deltas.
+ val loadResults = loadBatches(_delta, reader)
+ _delta.finishSnapshot()
+ info(s"Loaded snapshot ${reader.snapshotId().offset}-${reader.snapshotId().epoch}: " +
+ s"${loadResults}")
+ loadResults
} finally {
reader.close()
}
+ maybePublish(results.highestMetadataOffset)
}
+ }
- private def apply(batch: Batch[ApiMessageAndVersion]): Unit = {
- val records = batch.records
- val lastOffset = batch.lastOffset
+ case class BatchLoadResults(numBatches: Int,
+ numRecords: Int,
+ elapsedUs: Long,
+ highestMetadataOffset: Long) {
+ override def toString(): String = {
+ s"${numBatches} batch(es) with ${numRecords} record(s) ending at offset " +
+ s"${highestMetadataOffset} in ${elapsedUs} microseconds"
+ }
+ }
- if (isDebugEnabled) {
- debug(s"Metadata batch $lastOffset: handling ${records.size()} record(s).")
- }
- val imageBuilder =
- MetadataImageBuilder(brokerId, log, metadataCache.currentImage())
- val startNs = time.nanoseconds()
+ private def loadBatches(delta: MetadataDelta,
+ iterator: util.Iterator[Batch[ApiMessageAndVersion]]): BatchLoadResults = {
+ val startTimeNs = time.nanoseconds()
+ var numBatches = 0
+ var numRecords = 0
+ var newHighestMetadataOffset = _highestMetadataOffset
+ while (iterator.hasNext()) {
+ val batch = iterator.next()
var index = 0
- metadataBatchSizeHist.update(records.size())
- records.iterator().asScala.foreach { record =>
- try {
- if (isTraceEnabled) {
- trace("Metadata batch %d: processing [%d/%d]: %s.".format(lastOffset, index + 1,
- records.size(), record.toString))
- }
- handleMessage(imageBuilder, record.message, lastOffset)
- } catch {
- case e: Exception => error(s"Unable to handle record $index in batch " +
- s"ending at offset $lastOffset", e)
- }
- index = index + 1
- }
- if (imageBuilder.hasChanges) {
- val newImage = imageBuilder.build()
+ batch.records().forEach { messageAndVersion =>
+ newHighestMetadataOffset = batch.lastOffset()
if (isTraceEnabled) {
- trace(s"Metadata batch $lastOffset: creating new metadata image ${newImage}")
- } else if (isDebugEnabled) {
- debug(s"Metadata batch $lastOffset: creating new metadata image")
- }
- metadataCache.image(newImage)
- } else if (isDebugEnabled) {
- debug(s"Metadata batch $lastOffset: no new metadata image required.")
- }
- if (imageBuilder.hasPartitionChanges) {
- if (isDebugEnabled) {
- debug(s"Metadata batch $lastOffset: applying partition changes")
+ trace("Metadata batch %d: processing [%d/%d]: %s.".format(batch.lastOffset, index + 1,
+ batch.records().size(), messageAndVersion.message().toString()))
}
- replicaManager.handleMetadataRecords(imageBuilder, lastOffset,
- RequestHandlerHelper.onLeadershipChange(groupCoordinator, txnCoordinator, _, _))
- } else if (isDebugEnabled) {
- debug(s"Metadata batch $lastOffset: no partition changes found.")
+ delta.replay(messageAndVersion.message())
+ numRecords += 1
+ index += 1
}
- _highestMetadataOffset = lastOffset
- val endNs = time.nanoseconds()
- val deltaUs = TimeUnit.MICROSECONDS.convert(endNs - startNs, TimeUnit.NANOSECONDS)
- debug(s"Metadata batch $lastOffset: advanced highest metadata offset in ${deltaUs} " +
- "microseconds.")
- batchProcessingTimeHist.update(deltaUs)
+ metadataBatchSizeHist.update(batch.records().size())
+ numBatches = numBatches + 1
}
+ _highestMetadataOffset = newHighestMetadataOffset
+ val endTimeNs = time.nanoseconds()
+ val elapsedUs = TimeUnit.MICROSECONDS.convert(endTimeNs - startTimeNs, TimeUnit.NANOSECONDS)
+ batchProcessingTimeHist.update(elapsedUs)
+ BatchLoadResults(numBatches, numRecords, elapsedUs, newHighestMetadataOffset)
}
- private def handleMessage(imageBuilder: MetadataImageBuilder,
- record: ApiMessage,
- lastOffset: Long): Unit = {
- val recordType = try {
- fromId(record.apiKey())
- } catch {
- case e: Exception => throw new RuntimeException("Unknown metadata record type " +
- s"${record.apiKey()} in batch ending at offset ${lastOffset}.")
- }
-
- record match {
- case rec: RegisterBrokerRecord => handleRegisterBrokerRecord(imageBuilder, rec)
- case rec: UnregisterBrokerRecord => handleUnregisterBrokerRecord(imageBuilder, rec)
- case rec: FenceBrokerRecord => handleFenceBrokerRecord(imageBuilder, rec)
- case rec: UnfenceBrokerRecord => handleUnfenceBrokerRecord(imageBuilder, rec)
- case rec: TopicRecord => handleTopicRecord(imageBuilder, rec)
- case rec: PartitionRecord => handlePartitionRecord(imageBuilder, rec)
- case rec: PartitionChangeRecord => handlePartitionChangeRecord(imageBuilder, rec)
- case rec: RemoveTopicRecord => handleRemoveTopicRecord(imageBuilder, rec)
- case rec: ConfigRecord => handleConfigRecord(rec)
- case rec: ClientQuotaRecord => handleClientQuotaRecord(imageBuilder, rec)
- case rec: ProducerIdsRecord => handleProducerIdRecord(rec)
- case _ => throw new RuntimeException(s"Unhandled record $record with type $recordType")
- }
+ def startPublishing(publisher: MetadataPublisher): CompletableFuture[Void] = {
+ val event = new StartPublishingEvent(publisher)
+ eventQueue.append(event)
+ event.future
}
- def handleRegisterBrokerRecord(imageBuilder: MetadataImageBuilder,
- record: RegisterBrokerRecord): Unit = {
- val broker = MetadataBroker(record)
- imageBuilder.brokersBuilder().add(broker)
- }
-
- def handleUnregisterBrokerRecord(imageBuilder: MetadataImageBuilder,
- record: UnregisterBrokerRecord): Unit = {
- imageBuilder.brokersBuilder().remove(record.brokerId())
- }
-
- def handleTopicRecord(imageBuilder: MetadataImageBuilder,
- record: TopicRecord): Unit = {
- imageBuilder.partitionsBuilder().addUuidMapping(record.name(), record.topicId())
- }
+ class StartPublishingEvent(publisher: MetadataPublisher)
+ extends EventQueue.FailureLoggingEvent(log) {
+ val future = new CompletableFuture[Void]()
- def handlePartitionRecord(imageBuilder: MetadataImageBuilder,
- record: PartitionRecord): Unit = {
- imageBuilder.topicIdToName(record.topicId()) match {
- case None => throw new RuntimeException(s"Unable to locate topic with ID ${record.topicId}")
- case Some(name) =>
- val partition = MetadataPartition(name, record)
- imageBuilder.partitionsBuilder().set(partition)
+ override def run(): Unit = {
+ _publisher = Some(publisher)
+ log.info(s"Starting to publish metadata events at offset ${_highestMetadataOffset}.")
+ try {
+ maybePublish(_highestMetadataOffset)
+ future.complete(null)
+ } catch {
+ case e: Throwable => future.completeExceptionally(e)
+ }
}
}
- def handleConfigRecord(record: ConfigRecord): Unit = {
- val t = ConfigResource.Type.forId(record.resourceType())
- if (t == ConfigResource.Type.UNKNOWN) {
- throw new RuntimeException("Unable to understand config resource type " +
- s"${Integer.valueOf(record.resourceType())}")
+ private def maybePublish(newHighestMetadataOffset: Long): Unit = {
+ _publisher match {
+ case None => // Nothing to do
+ case Some(publisher) => {
+ val delta = _delta
+ _image = _delta.apply()
+ _delta = new MetadataDelta(_image)
+ publisher.publish(newHighestMetadataOffset, delta, _image)
+ }
}
- val resource = new ConfigResource(t, record.resourceName())
- configRepository.setConfig(resource, record.name(), record.value())
- }
-
- def handlePartitionChangeRecord(imageBuilder: MetadataImageBuilder,
- record: PartitionChangeRecord): Unit = {
- imageBuilder.partitionsBuilder().handleChange(record)
}
- def handleFenceBrokerRecord(imageBuilder: MetadataImageBuilder,
- record: FenceBrokerRecord): Unit = {
- // TODO: add broker epoch to metadata cache, and check it here.
- imageBuilder.brokersBuilder().changeFencing(record.id(), fenced = true)
+ override def handleLeaderChange(leaderAndEpoch: LeaderAndEpoch): Unit = {
+ // TODO: cache leaderAndEpoch so we can use the epoch in broker-initiated snapshots.
}
- def handleUnfenceBrokerRecord(imageBuilder: MetadataImageBuilder,
- record: UnfenceBrokerRecord): Unit = {
- // TODO: add broker epoch to metadata cache, and check it here.
- imageBuilder.brokersBuilder().changeFencing(record.id(), fenced = false)
+ override def beginShutdown(): Unit = {
+ eventQueue.beginShutdown("beginShutdown", new ShutdownEvent())
}
- def handleRemoveTopicRecord(imageBuilder: MetadataImageBuilder,
- record: RemoveTopicRecord): Unit = {
- imageBuilder.topicIdToName(record.topicId()) match {
- case None =>
- throw new RuntimeException(s"Unable to locate topic with ID ${record.topicId}")
-
- case Some(topicName) =>
- info(s"Processing deletion of topic $topicName with id ${record.topicId}")
- val removedPartitions = imageBuilder.partitionsBuilder().removeTopicById(record.topicId())
- groupCoordinator.handleDeletedPartitions(removedPartitions.map(_.toTopicPartition).toSeq, RequestLocal.NoCaching)
- configRepository.remove(new ConfigResource(ConfigResource.Type.TOPIC, topicName))
+ class ShutdownEvent() extends EventQueue.FailureLoggingEvent(log) {
+ override def run(): Unit = {
+ removeMetric(BrokerMetadataListener.MetadataBatchProcessingTimeUs)
+ removeMetric(BrokerMetadataListener.MetadataBatchSizes)
}
}
- def handleClientQuotaRecord(imageBuilder: MetadataImageBuilder,
- record: ClientQuotaRecord): Unit = {
- // TODO add quotas to MetadataImageBuilder
- clientQuotaManager.handleQuotaRecord(record)
+ def close(): Unit = {
+ beginShutdown()
+ eventQueue.close()
}
- def handleProducerIdRecord(record: ProducerIdsRecord): Unit = {
- // This is a no-op since brokers get their producer ID blocks directly from the controller via
- // AllocateProducerIds RPC response
+ // VisibleForTesting
+ private[kafka] def getImageRecords(): CompletableFuture[util.List[ApiMessageAndVersion]] = {
+ val future = new CompletableFuture[util.List[ApiMessageAndVersion]]()
+ eventQueue.append(new GetImageRecordsEvent(future))
+ future
}
- class HandleNewLeaderEvent(leaderAndEpoch: LeaderAndEpoch)
- extends EventQueue.FailureLoggingEvent(log) {
- override def run(): Unit = {
- val imageBuilder =
- MetadataImageBuilder(brokerId, log, metadataCache.currentImage())
- imageBuilder.controllerId(leaderAndEpoch.leaderId.asScala)
- metadataCache.image(imageBuilder.build())
+ class GetImageRecordsEvent(future: CompletableFuture[util.List[ApiMessageAndVersion]])
+ extends EventQueue.FailureLoggingEvent(log) with Consumer[util.List[ApiMessageAndVersion]] {
+ val records = new util.ArrayList[ApiMessageAndVersion]()
+ override def accept(batch: util.List[ApiMessageAndVersion]): Unit = {
+ if (batch == null) {
Review comment:
You're right, there is no need for the null here. Removed.
--
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] jacky1193610322 commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
jacky1193610322 commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r660204460
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
I'm sorry too, I have no problem if we always replay each record once and exactly once even if the broker crash.
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r660141890
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
Sorry, I can't quite follow the question. It is certainly the case that we only replay each record once and exactly once, though, if that's the question?
--
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] hachikuji commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
hachikuji commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663154812
##########
File path: core/src/main/scala/kafka/server/ReplicaManager.scala
##########
@@ -2032,4 +2001,207 @@ class ReplicaManager(val config: KafkaConfig,
}
}
+ private[kafka] def getOrCreatePartition(tp: TopicPartition,
+ delta: TopicsDelta,
+ topicId: Uuid): Option[(Partition, Boolean)] = {
+ getPartition(tp) match {
+ case HostedPartition.Offline =>
+ stateChangeLogger.warn(s"Unable to bring up new local leader ${tp} " +
+ s"with topic id ${topicId} because it resides in an offline log " +
+ "directory.")
+ None
+
+ case HostedPartition.Online(partition) => Some(partition, false)
Review comment:
Should we validate the topicId matches?
##########
File path: core/src/main/scala/kafka/server/ReplicaManager.scala
##########
@@ -2032,4 +2001,207 @@ class ReplicaManager(val config: KafkaConfig,
}
}
+ private[kafka] def getOrCreatePartition(tp: TopicPartition,
+ delta: TopicsDelta,
+ topicId: Uuid): Option[(Partition, Boolean)] = {
+ getPartition(tp) match {
+ case HostedPartition.Offline =>
+ stateChangeLogger.warn(s"Unable to bring up new local leader ${tp} " +
+ s"with topic id ${topicId} because it resides in an offline log " +
+ "directory.")
+ None
+
+ case HostedPartition.Online(partition) => Some(partition, false)
+
+ case HostedPartition.None =>
+ if (delta.image().topicsById().containsKey(topicId)) {
+ stateChangeLogger.error(s"Expected partition ${tp} with topic id " +
+ s"${topicId} to exist, but it was missing. Creating...")
+ } else {
+ stateChangeLogger.info(s"Creating new partition ${tp} with topic id " +
+ s"${topicId}.")
+ }
+ // it's a partition that we don't know about yet, so create it and mark it online
+ val partition = Partition(tp, time, this)
+ allPartitions.put(tp, HostedPartition.Online(partition))
+ Some(partition, true)
+ }
+ }
+
+ private[kafka] def calculateDeltaChanges(delta: TopicsDelta)
+ : (mutable.HashMap[TopicPartition, Boolean],
+ mutable.HashMap[TopicPartition, LocalLeaderInfo],
+ mutable.HashMap[TopicPartition, LocalLeaderInfo]) = {
+ val deleted = new mutable.HashMap[TopicPartition, Boolean]()
+ delta.deletedTopicIds().forEach { topicId =>
+ val topicImage = delta.image().getTopic(topicId)
+ topicImage.partitions().keySet().forEach { partitionId =>
+ deleted.put(new TopicPartition(topicImage.name(), partitionId), true)
+ }
+ }
+ val newLocalLeaders = new mutable.HashMap[TopicPartition, LocalLeaderInfo]()
+ val newLocalFollowers = new mutable.HashMap[TopicPartition, LocalLeaderInfo]()
+ delta.changedTopics().values().forEach { topicDelta =>
+ topicDelta.newLocalLeaders(config.nodeId).forEach { e =>
+ newLocalLeaders.put(new TopicPartition(topicDelta.name(), e.getKey),
+ LocalLeaderInfo(topicDelta.id(), e.getValue))
+ }
+ topicDelta.newLocalFollowers(config.nodeId).forEach { e =>
+ newLocalFollowers.put(new TopicPartition(topicDelta.name(), e.getKey),
+ LocalLeaderInfo(topicDelta.id(), e.getValue))
+ }
+ }
+ (deleted, newLocalLeaders, newLocalFollowers)
+ }
+
+ /**
+ * Apply a KRaft topic change delta.
+ *
+ * @param newImage The new metadata image.
+ * @param delta The delta to apply.
+ */
+ def applyDelta(newImage: MetadataImage, delta: TopicsDelta): Unit = {
+ // Before taking the lock, build some hash maps that we will need.
+ val (deleted, newLocalLeaders, newLocalFollowers) = calculateDeltaChanges(delta)
+
+ replicaStateChangeLock.synchronized {
+ // Handle deleted partitions. We need to do this first because we might subsequently
+ // create new partitions with the same names as the ones we are deleting here.
+ if (!deleted.isEmpty) {
+ stateChangeLogger.info(s"Deleting ${deleted.size} partition(s).")
+ stopPartitions(deleted).foreach { case (topicPartition, e) =>
+ if (e.isInstanceOf[KafkaStorageException]) {
+ stateChangeLogger.error(s"Unable to delete replica ${topicPartition} because " +
+ "the local replica for the partition is in an offline log directory")
+ } else {
+ stateChangeLogger.error(s"Unable to delete replica ${topicPartition} because " +
+ s"we got an unexpected ${e.getClass.getName} exception: ${e.getMessage}")
+ }
+ }
+ }
+ // Handle partitions which we are now the leader or follower for.
+ if (!newLocalLeaders.isEmpty || !newLocalFollowers.isEmpty) {
+ val lazyOffsetCheckpoints = new LazyOffsetCheckpoints(this.highWatermarkCheckpoints)
+ val changedPartitions = new mutable.HashSet[Partition]
+ if (!newLocalLeaders.isEmpty) {
+ applyLocalLeadersDelta(changedPartitions, delta, lazyOffsetCheckpoints, newLocalLeaders)
+ }
+ if (!newLocalFollowers.isEmpty) {
+ applyLocalFollowersDelta(changedPartitions, newImage, delta, lazyOffsetCheckpoints, newLocalFollowers)
+ }
+ maybeAddLogDirFetchers(changedPartitions, lazyOffsetCheckpoints,
+ name => Option(newImage.topics().getTopic(name)).map(_.id()))
+
+ def markPartitionOfflineIfNeeded(tp: TopicPartition): Unit = {
+ /*
+ * If there is offline log directory, a Partition object may have been created by getOrCreatePartition()
+ * before getOrCreateReplica() failed to create local replica due to KafkaStorageException.
+ * In this case ReplicaManager.allPartitions will map this topic-partition to an empty Partition object.
+ * we need to map this topic-partition to OfflinePartition instead.
+ */
+ if (localLog(tp).isEmpty)
+ markPartitionOffline(tp)
+ }
+ newLocalLeaders.keySet.foreach(markPartitionOfflineIfNeeded(_))
+ newLocalFollowers.keySet.foreach(markPartitionOfflineIfNeeded(_))
+
+ replicaFetcherManager.shutdownIdleFetcherThreads()
+ replicaAlterLogDirsManager.shutdownIdleFetcherThreads()
+ }
+ }
+ }
+
+ private def applyLocalLeadersDelta(changedPartitions: mutable.HashSet[Partition],
+ delta: TopicsDelta,
+ offsetCheckpoints: OffsetCheckpoints,
+ newLocalLeaders: mutable.HashMap[TopicPartition, LocalLeaderInfo]): Unit = {
+ stateChangeLogger.info(s"Transitioning ${newLocalLeaders.size} partition(s) to " +
+ "local leaders.")
+ replicaFetcherManager.removeFetcherForPartitions(newLocalLeaders.keySet)
+ newLocalLeaders.forKeyValue { case (tp, info) =>
+ getOrCreatePartition(tp, delta, info.topicId).foreach { case (partition, isNew) =>
+ try {
+ val state = info.partition.toLeaderAndIsrPartitionState(tp, isNew)
+ if (!partition.makeLeader(state, offsetCheckpoints, Some(info.topicId))) {
+ stateChangeLogger.info("Skipped the become-leader state change for " +
+ s"${tp} with topic id ${info.topicId} because this partition is " +
+ "already a local leader.")
+ }
+ changedPartitions.add(partition)
+ } catch {
+ case e: KafkaStorageException =>
+ stateChangeLogger.info(s"Skipped the become-leader state change for ${tp} " +
+ s"with topic id ${info.topicId} due to disk error ${e}")
+ val dirOpt = getLogDir(tp)
+ error(s"Error while making broker the leader for partition ${tp} in dir " +
+ s"${dirOpt}", e)
+ }
+ }
+ }
+ }
+
+ private def applyLocalFollowersDelta(changedPartitions: mutable.HashSet[Partition],
+ newImage: MetadataImage,
+ delta: TopicsDelta,
+ offsetCheckpoints: OffsetCheckpoints,
+ newLocalFollowers: mutable.HashMap[TopicPartition, LocalLeaderInfo]): Unit = {
+ stateChangeLogger.info(s"Transitioning ${newLocalFollowers.size} partition(s) to " +
+ "local followers.")
+ replicaFetcherManager.removeFetcherForPartitions(newLocalFollowers.keySet)
+ val shuttingDown = isShuttingDown.get()
+ val partitionsToMakeFollower = new mutable.HashMap[TopicPartition, InitialFetchState]
+ val newFollowerTopicSet = new mutable.HashSet[String]
+ newLocalFollowers.forKeyValue { case (tp, info) =>
+ getOrCreatePartition(tp, delta, info.topicId).foreach { case (partition, isNew) =>
+ try {
+ newFollowerTopicSet.add(tp.topic())
+
+ completeDelayedFetchOrProduceRequests(tp)
+
+ // Create the local replica even if the leader is unavailable. This is required
+ // to ensure that we include the partition's high watermark in the checkpoint
+ // file (see KAFKA-1647)
+ partition.createLogIfNotExists(isNew, false, offsetCheckpoints, Some(info.topicId))
+
+ if (shuttingDown) {
+ stateChangeLogger.trace(s"Unable to start fetching ${tp} with topic " +
+ s"ID ${info.topicId} because the replica manager is shutting down.")
+ } else {
+ val listenerName = config.interBrokerListenerName.value()
+ val leader = info.partition.leader
+ Option(newImage.cluster().broker(leader)).flatMap(_.node(listenerName).asScala) match {
+ case None => stateChangeLogger.trace(s"Unable to start fetching ${tp} " +
+ s"with topic ID ${info.topicId} from leader ${leader} because it is not " +
+ "alive.")
+ case Some(node) =>
+ val leaderEndPoint = new BrokerEndPoint(node.id(), node.host(), node.port())
+ val log = partition.localLogOrException
+ val fetchOffset = initialFetchOffset(log)
+ partitionsToMakeFollower.put(tp,
+ InitialFetchState(leaderEndPoint, partition.getLeaderEpoch, fetchOffset))
+ }
+ }
+ changedPartitions.add(partition)
+ } catch {
+ case e: Throwable => stateChangeLogger.error(s"Unable to start fetching ${tp} " +
Review comment:
Perhaps we should consider adding this partition to the failed partitions that are tracked in the ReplicaFetcherManager.
##########
File path: core/src/main/scala/kafka/server/metadata/BrokerMetadataListener.scala
##########
@@ -70,230 +58,188 @@ class BrokerMetadataListener(
*/
@volatile private var _highestMetadataOffset = -1L
+ /**
+ * The current broker metadata image. Accessed only from the event queue thread.
+ */
+ private var _image = MetadataImage.EMPTY
+
+ /**
+ * The current metadata delta. Accessed only from the event queue thread.
+ */
+ private var _delta = new MetadataDelta(_image)
+
+ /**
+ * The object to use to publish new metadata changes, or None if this listener has not
+ * been activated yet.
+ */
+ private var _publisher: Option[MetadataPublisher] = None
+
+ /**
+ * The event queue which runs this listener.
+ */
val eventQueue = new KafkaEventQueue(time, logContext, threadNamePrefix.getOrElse(""))
+ /**
+ * Returns the highest metadata-offset. Thread-safe.
+ */
def highestMetadataOffset(): Long = _highestMetadataOffset
/**
* Handle new metadata records.
*/
- override def handleCommit(reader: BatchReader[ApiMessageAndVersion]): Unit = {
+ override def handleCommit(reader: BatchReader[ApiMessageAndVersion]): Unit =
eventQueue.append(new HandleCommitsEvent(reader))
+
+ class HandleCommitsEvent(reader: BatchReader[ApiMessageAndVersion])
+ extends EventQueue.FailureLoggingEvent(log) {
+ override def run(): Unit = {
+ val results = try {
+ val loadResults = loadBatches(_delta, reader)
+ if (isDebugEnabled) {
+ debug(s"Loaded new commits: ${loadResults}")
+ }
+ loadResults
+ } finally {
+ reader.close()
+ }
+ maybePublish(results.highestMetadataOffset)
+ }
}
/**
* Handle metadata snapshots
*/
- override def handleSnapshot(reader: SnapshotReader[ApiMessageAndVersion]): Unit = {
- // Loading snapshot on the broker is currently not supported.
- reader.close();
- throw new UnsupportedOperationException(s"Loading snapshot (${reader.snapshotId()}) is not supported")
- }
-
- // Visible for testing. It's useful to execute events synchronously in order
- // to make tests deterministic. This object is responsible for closing the reader.
- private[metadata] def execCommits(batchReader: BatchReader[ApiMessageAndVersion]): Unit = {
- new HandleCommitsEvent(batchReader).run()
- }
+ override def handleSnapshot(reader: SnapshotReader[ApiMessageAndVersion]): Unit =
+ eventQueue.append(new HandleSnapshotEvent(reader))
- class HandleCommitsEvent(
- reader: BatchReader[ApiMessageAndVersion]
- ) extends EventQueue.FailureLoggingEvent(log) {
+ class HandleSnapshotEvent(reader: SnapshotReader[ApiMessageAndVersion])
+ extends EventQueue.FailureLoggingEvent(log) {
override def run(): Unit = {
- try {
- while (reader.hasNext()) {
- apply(reader.next())
- }
+ val results = try {
+ info(s"Loading snapshot ${reader.snapshotId().offset}-${reader.snapshotId().epoch}.")
+ _delta = new MetadataDelta(_image) // Discard any previous deltas.
+ val loadResults = loadBatches(_delta, reader)
+ _delta.finishSnapshot()
Review comment:
I found this part to be confusing at first, but I think I get it now. Basically the purpose of `finishSnapshot` is to ensure that any keys present in the old image but not the new image get removed in the delta. Do I have that right? I suspect we can improve the name, but I'm not sure I have any great suggestions. At least it would be useful to document somewhere how the api works.
##########
File path: core/src/main/scala/kafka/server/metadata/ClientQuotaMetadataManager.scala
##########
@@ -115,36 +117,28 @@ class ClientQuotaMetadataManager(private[metadata] val quotaManagers: QuotaManag
case _ => throw new IllegalStateException("Should only handle IP quota entities here")
}
- // The connection quota only understands the connection rate limit
- if (quotaRecord.key() != QuotaConfigs.IP_CONNECTION_RATE_OVERRIDE_CONFIG) {
- warn(s"Ignoring unexpected quota key ${quotaRecord.key()} for entity $ipEntity")
- return
- }
-
- // Convert the value to an appropriate Option for the quota manager
- val newValue = if (quotaRecord.remove()) {
- None
- } else {
- Some(quotaRecord.value).map(_.toInt)
- }
- try {
- connectionQuotas.updateIpConnectionRateQuota(inetAddress, newValue)
- } catch {
- case t: Throwable => error(s"Failed to update IP quota $ipEntity", t)
+ quotaDelta.changes().entrySet().forEach { e =>
+ // The connection quota only understands the connection rate limit
+ if (!e.getKey().equals(QuotaConfigs.IP_CONNECTION_RATE_OVERRIDE_CONFIG)) {
Review comment:
nit: it would make the code a little more readable if use used vals with good names for `e.getKey` and `e.getValue`
##########
File path: core/src/main/scala/kafka/server/metadata/BrokerMetadataListener.scala
##########
@@ -70,230 +58,188 @@ class BrokerMetadataListener(
*/
@volatile private var _highestMetadataOffset = -1L
+ /**
+ * The current broker metadata image. Accessed only from the event queue thread.
+ */
+ private var _image = MetadataImage.EMPTY
+
+ /**
+ * The current metadata delta. Accessed only from the event queue thread.
+ */
+ private var _delta = new MetadataDelta(_image)
+
+ /**
+ * The object to use to publish new metadata changes, or None if this listener has not
+ * been activated yet.
+ */
+ private var _publisher: Option[MetadataPublisher] = None
+
+ /**
+ * The event queue which runs this listener.
+ */
val eventQueue = new KafkaEventQueue(time, logContext, threadNamePrefix.getOrElse(""))
+ /**
+ * Returns the highest metadata-offset. Thread-safe.
+ */
def highestMetadataOffset(): Long = _highestMetadataOffset
/**
* Handle new metadata records.
*/
- override def handleCommit(reader: BatchReader[ApiMessageAndVersion]): Unit = {
+ override def handleCommit(reader: BatchReader[ApiMessageAndVersion]): Unit =
eventQueue.append(new HandleCommitsEvent(reader))
+
+ class HandleCommitsEvent(reader: BatchReader[ApiMessageAndVersion])
+ extends EventQueue.FailureLoggingEvent(log) {
+ override def run(): Unit = {
+ val results = try {
+ val loadResults = loadBatches(_delta, reader)
+ if (isDebugEnabled) {
+ debug(s"Loaded new commits: ${loadResults}")
+ }
+ loadResults
+ } finally {
+ reader.close()
+ }
+ maybePublish(results.highestMetadataOffset)
+ }
}
/**
* Handle metadata snapshots
*/
- override def handleSnapshot(reader: SnapshotReader[ApiMessageAndVersion]): Unit = {
- // Loading snapshot on the broker is currently not supported.
- reader.close();
- throw new UnsupportedOperationException(s"Loading snapshot (${reader.snapshotId()}) is not supported")
- }
-
- // Visible for testing. It's useful to execute events synchronously in order
- // to make tests deterministic. This object is responsible for closing the reader.
- private[metadata] def execCommits(batchReader: BatchReader[ApiMessageAndVersion]): Unit = {
- new HandleCommitsEvent(batchReader).run()
- }
+ override def handleSnapshot(reader: SnapshotReader[ApiMessageAndVersion]): Unit =
+ eventQueue.append(new HandleSnapshotEvent(reader))
- class HandleCommitsEvent(
- reader: BatchReader[ApiMessageAndVersion]
- ) extends EventQueue.FailureLoggingEvent(log) {
+ class HandleSnapshotEvent(reader: SnapshotReader[ApiMessageAndVersion])
+ extends EventQueue.FailureLoggingEvent(log) {
override def run(): Unit = {
- try {
- while (reader.hasNext()) {
- apply(reader.next())
- }
+ val results = try {
+ info(s"Loading snapshot ${reader.snapshotId().offset}-${reader.snapshotId().epoch}.")
+ _delta = new MetadataDelta(_image) // Discard any previous deltas.
+ val loadResults = loadBatches(_delta, reader)
+ _delta.finishSnapshot()
+ info(s"Loaded snapshot ${reader.snapshotId().offset}-${reader.snapshotId().epoch}: " +
+ s"${loadResults}")
+ loadResults
} finally {
reader.close()
}
+ maybePublish(results.highestMetadataOffset)
}
+ }
- private def apply(batch: Batch[ApiMessageAndVersion]): Unit = {
- val records = batch.records
- val lastOffset = batch.lastOffset
+ case class BatchLoadResults(numBatches: Int,
+ numRecords: Int,
+ elapsedUs: Long,
+ highestMetadataOffset: Long) {
+ override def toString(): String = {
+ s"${numBatches} batch(es) with ${numRecords} record(s) ending at offset " +
+ s"${highestMetadataOffset} in ${elapsedUs} microseconds"
+ }
+ }
- if (isDebugEnabled) {
- debug(s"Metadata batch $lastOffset: handling ${records.size()} record(s).")
- }
- val imageBuilder =
- MetadataImageBuilder(brokerId, log, metadataCache.currentImage())
- val startNs = time.nanoseconds()
+ private def loadBatches(delta: MetadataDelta,
+ iterator: util.Iterator[Batch[ApiMessageAndVersion]]): BatchLoadResults = {
Review comment:
nit: misaligned
##########
File path: core/src/main/scala/kafka/server/metadata/MetadataPublisher.scala
##########
@@ -0,0 +1,25 @@
+/**
+ * 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.metadata
+
+import org.apache.kafka.image.{MetadataDelta, MetadataImage}
+
+trait MetadataPublisher {
+ def publish(newHighestMetadataOffset: Long,
Review comment:
Might be helpful to have a doc here. Specifically I think it's useful to note that the new image is the result of applying the passed delta to the previous image.
--
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] jacky1193610322 commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
jacky1193610322 commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r660204460
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
I'm sorry too, I have no question if we always replay each record once and exactly once even if the broker crash.
--
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] cmccabe commented on pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#issuecomment-875047031
Sorry, I forgot to push earlier. Also fixed an additional issue with default quotas.
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663276540
##########
File path: core/src/main/scala/kafka/server/ReplicaManager.scala
##########
@@ -2032,4 +2001,207 @@ class ReplicaManager(val config: KafkaConfig,
}
}
+ private[kafka] def getOrCreatePartition(tp: TopicPartition,
+ delta: TopicsDelta,
+ topicId: Uuid): Option[(Partition, Boolean)] = {
+ getPartition(tp) match {
+ case HostedPartition.Offline =>
+ stateChangeLogger.warn(s"Unable to bring up new local leader ${tp} " +
+ s"with topic id ${topicId} because it resides in an offline log " +
+ "directory.")
+ None
+
+ case HostedPartition.Online(partition) => Some(partition, false)
Review comment:
It's a bit messy because actually the topic ID is not stored in the Partition object, but in the Log object, which may not actually exist (although we'd want to transition out of online mode eventually if that were the case, of course.) I will add a check that if the id is defined it's correct, though.
--
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] jacky1193610322 commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
jacky1193610322 commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r660054798
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
Thanks for your reply, it's right if will always keep the delta not replay before, which means we must persist the checkpoint offset every commit, but now we are not. for example, if the broker crash, we maybe replay the latest snapshot and the delta after the snapshot offset, but it may be the delta after the snapshot has been replay before. I don't sure it's right? 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] hachikuji commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
hachikuji commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663403189
##########
File path: core/src/main/scala/kafka/server/BrokerServer.scala
##########
@@ -340,7 +338,8 @@ class BrokerServer(
SocketServer.DataPlaneThreadPrefix)
if (socketServer.controlPlaneRequestChannelOpt.isDefined) {
- throw new RuntimeException("KIP-291 endpoints are not supported when in KRaft mode.")
+ throw new RuntimeException("KIP-291 control plane listeners are not supported " +
Review comment:
nit: you might have missed my comment. Can we mention the configuration `control.plane.listener.name` explicitly instead of KIP-291?
##########
File path: core/src/main/scala/kafka/server/ReplicaManager.scala
##########
@@ -2011,7 +2011,16 @@ class ReplicaManager(val config: KafkaConfig,
"directory.")
None
- case HostedPartition.Online(partition) => Some(partition, false)
+ case HostedPartition.Online(partition) => {
+ if (partition.topicId.isDefined && !partition.topicId.equals(topicId)) {
Review comment:
The second check here is not right since `topicId` is not an option. I think what we want is this?
```scala
if (partition.topicId.exists(_ != topicId)) {
```
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r659940260
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
If the topic is created and then deleted within the same delta, the topic log dir is never created, so there is no need for it to be deleted.
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
Sorry, I can't quite follow the question. It is certainly the case that we only replay each record once and exactly once, though, if that's the question?
--
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] jacky1193610322 commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
jacky1193610322 commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r659292704
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
`Topics that are created and then deleted within the same delta will leave no trace.`
if do this, we will not delete the topic log dir and some other file.
Maybe we need a timeline, which can compact the partition change event but can't compact the create topic event and delete topic event. I create a jira before. [jira](https://issues.apache.org/jira/browse/KAFKA-12682)
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663269838
##########
File path: core/src/main/scala/kafka/server/BrokerServer.scala
##########
@@ -264,19 +266,13 @@ class BrokerServer(
/* Add all reconfigurables for config change notification before starting the metadata listener */
config.dynamicConfig.addReconfigurables(this)
- val clientQuotaMetadataManager = new ClientQuotaMetadataManager(
- quotaManagers, socketServer.connectionQuotas, quotaCache)
+ // TODO : check that we're properly handling "ConfigType" Client, User, and Ip (which are not
Review comment:
I'll take a look next week when I add more tests. The quotas stuff should be handled through the client quotas manager.
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663274842
##########
File path: core/src/main/scala/kafka/server/metadata/BrokerMetadataPublisher.scala
##########
@@ -0,0 +1,249 @@
+/**
+ * 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.metadata
+
+import kafka.coordinator.group.GroupCoordinator
+import kafka.coordinator.transaction.TransactionCoordinator
+import kafka.log.{Log, LogManager}
+import kafka.server.ConfigType
+import kafka.server.{ConfigHandler, FinalizedFeatureCache, KafkaConfig, ReplicaManager, RequestLocal}
+import kafka.utils.Logging
+import org.apache.kafka.common.TopicPartition
+import org.apache.kafka.common.config.ConfigResource
+import org.apache.kafka.common.internals.Topic
+import org.apache.kafka.image.{MetadataDelta, MetadataImage, TopicDelta}
+
+import scala.collection.mutable
+
+
+object BrokerMetadataPublisher {
+ /**
+ * Given a topic name, find out if it changed. Note: if a topic named X was deleted and
+ * then re-created, this method will return just the re-creation. The deletion will show
+ * up in deletedTopicIds and must be handled separately.
+ *
+ * @param topicName The topic name.
+ * @param newImage The new metadata image.
+ * @param delta The metadata delta to search.
+ *
+ * @return The delta, or None if appropriate.
+ */
+ def getTopicDelta(topicName: String,
+ newImage: MetadataImage,
+ delta: MetadataDelta): Option[TopicDelta] = {
+ Option(newImage.topics().getTopic(topicName)).map {
+ topicImage => delta.topicsDelta().changedTopic(topicImage.id())
+ }
+ }
+
+ /**
+ * Find logs which should not be on the current broker, according to the metadata image.
+ *
+ * @param brokerId The ID of the current broker.
+ * @param newImage The metadata image.
+ * @param logs A collection of Log objects.
+ *
+ * @return The topic partitions which are no longer needed on this broker.
+ */
+ def findGhostReplicas(brokerId: Int,
+ newImage: MetadataImage,
+ logs: Iterable[Log]): Iterable[TopicPartition] = {
+ logs.flatMap { log =>
+ log.topicId match {
+ case None => throw new RuntimeException(s"Topic ${log.name} does not have a topic ID, " +
+ "which is not allowed when running in KRaft mode.")
+ case Some(topicId) =>
+ val partitionId = log.topicPartition.partition()
+ Option(newImage.topics().getPartition(topicId, partitionId)) match {
+ case None => None
+ case Some(partition) => if (partition.replicas.contains(brokerId)) {
+ Some(log.topicPartition)
+ } else {
+ None
+ }
+ }
+ }
+ }
+ }
+}
+
+class BrokerMetadataPublisher(conf: KafkaConfig,
+ metadataCache: KRaftMetadataCache,
+ logManager: LogManager,
+ replicaManager: ReplicaManager,
+ groupCoordinator: GroupCoordinator,
+ txnCoordinator: TransactionCoordinator,
+ clientQuotaMetadataManager: ClientQuotaMetadataManager,
+ featureCache: FinalizedFeatureCache,
+ dynamicConfigHandlers: Map[String, ConfigHandler]) extends MetadataPublisher with Logging {
+ logIdent = s"[BrokerMetadataPublisher id=${conf.nodeId}] "
+
+ import BrokerMetadataPublisher._
+
+ /**
+ * The broker ID.
+ */
+ val brokerId = conf.nodeId
+
+ /**
+ * True if this is the first time we have published metadata.
+ */
+ var _firstPublish = false
+
+ override def publish(newHighestMetadataOffset: Long,
+ delta: MetadataDelta,
+ newImage: MetadataImage): Unit = {
+ try {
+ // Publish the new metadata image to the metadata cache.
+ metadataCache.setImage(newImage)
+
+ if (_firstPublish) {
+ info(s"Publishing initial metadata at offset ${newHighestMetadataOffset}.")
+
+ // If this is the first metadata update we are applying, initialize the managers
+ // first (but after setting up the metadata cache).
+ initializeManagers()
+ } else if (isDebugEnabled) {
+ debug(s"Publishing metadata at offset ${newHighestMetadataOffset}.")
+ }
+
+ // Apply feature deltas.
+ Option(delta.featuresDelta()).foreach { featuresDelta =>
+ featureCache.update(featuresDelta, newHighestMetadataOffset)
+ }
+
+ // Apply topic deltas.
+ Option(delta.topicsDelta()).foreach { topicsDelta =>
+ // Notify the replica manager about changes to topics.
+ replicaManager.applyDelta(newImage, topicsDelta)
+
+ // Handle the case where the old consumer offsets topic was deleted.
+ if (topicsDelta.topicWasDeleted(Topic.GROUP_METADATA_TOPIC_NAME)) {
+ topicsDelta.image().getTopic(Topic.GROUP_METADATA_TOPIC_NAME).partitions().entrySet().forEach {
+ entry =>
+ if (entry.getValue().leader == brokerId) {
+ groupCoordinator.onResignation(entry.getKey(), Some(entry.getValue().leaderEpoch))
+ }
+ }
+ }
+ // Handle the case where we have new local leaders or followers for the consumer
+ // offsets topic.
+ getTopicDelta(Topic.GROUP_METADATA_TOPIC_NAME, newImage, delta).foreach { topicDelta =>
+ topicDelta.newLocalLeaders(brokerId).forEach {
+ entry => groupCoordinator.onElection(entry.getKey(), entry.getValue().leaderEpoch)
+ }
+ topicDelta.newLocalFollowers(brokerId).forEach {
+ entry => groupCoordinator.onResignation(entry.getKey(), Some(entry.getValue().leaderEpoch))
+ }
+ }
+
+ // Handle the case where the old transaction state topic was deleted.
+ if (topicsDelta.topicWasDeleted(Topic.TRANSACTION_STATE_TOPIC_NAME)) {
+ topicsDelta.image().getTopic(Topic.TRANSACTION_STATE_TOPIC_NAME).partitions().entrySet().forEach {
+ entry =>
+ if (entry.getValue().leader == brokerId) {
+ txnCoordinator.onResignation(entry.getKey(), Some(entry.getValue().leaderEpoch))
+ }
+ }
+ }
+ // If the transaction state topic changed in a way that's relevant to this broker,
+ // notify the transaction coordinator.
+ getTopicDelta(Topic.TRANSACTION_STATE_TOPIC_NAME, newImage, delta).foreach { topicDelta =>
+ topicDelta.newLocalLeaders(brokerId).forEach {
+ entry => txnCoordinator.onElection(entry.getKey(), entry.getValue().leaderEpoch)
+ }
+ topicDelta.newLocalFollowers(brokerId).forEach {
+ entry => txnCoordinator.onResignation(entry.getKey(), Some(entry.getValue().leaderEpoch))
+ }
+ }
+
+ // Notify the group coordinator about deleted topics.
+ val deletedTopicPartitions = new mutable.ArrayBuffer[TopicPartition]()
+ topicsDelta.deletedTopicIds().forEach { id =>
+ val topicImage = topicsDelta.image().getTopic(id)
+ topicImage.partitions().keySet().forEach {
+ id => deletedTopicPartitions += new TopicPartition(topicImage.name(), id)
+ }
+ }
+ if (!deletedTopicPartitions.isEmpty) {
+ groupCoordinator.handleDeletedPartitions(deletedTopicPartitions, RequestLocal.NoCaching)
+ }
+ }
+
+ // Apply configuration deltas.
+ Option(delta.configsDelta()).foreach { configsDelta =>
+ configsDelta.changes().keySet().forEach { configResource =>
+ val tag = configResource.`type`() match {
+ case ConfigResource.Type.TOPIC => Some(ConfigType.Topic)
+ case ConfigResource.Type.BROKER => Some(ConfigType.Broker)
+ case _ => None
+ }
+ tag.foreach { t =>
+ val newProperties = newImage.configs().configProperties(configResource)
+ dynamicConfigHandlers(t).processConfigChanges(configResource.name(), newProperties)
+ }
+ }
+ }
+
+ // Apply client quotas delta.
+ Option(delta.clientQuotasDelta()).foreach { clientQuotasDelta =>
+ clientQuotaMetadataManager.update(clientQuotasDelta)
+ }
+
+ if (_firstPublish) {
+ finishInitializingReplicaManager(newImage)
+ }
+ } catch {
+ case t: Throwable => error(s"Error publishing broker metadata at ${newHighestMetadataOffset}", t)
+ throw t
+ } finally {
+ _firstPublish = false
+ }
+ }
+
+ private def initializeManagers(): Unit = {
+ // Start log manager, which will perform (potentially lengthy)
+ // recovery-from-unclean-shutdown if required.
+ logManager.startup(metadataCache.getAllTopics())
+
+ // Start the replica manager.
+ replicaManager.startup()
Review comment:
I was thinking about that too. If I can find a way to condense the initialization into a single startup callback, I'll try to put the code back into `BrokerServer`. It still needs to happen in the context of the metadata listener thread, though.
--
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] mumrah commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
mumrah commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r661516512
##########
File path: metadata/src/main/java/org/apache/kafka/image/ClientQuotasImage.java
##########
@@ -0,0 +1,178 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.message.DescribeClientQuotasRequestData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData.EntityData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData.EntryData;
+import org.apache.kafka.common.quota.ClientQuotaEntity;
+import org.apache.kafka.server.common.ApiMessageAndVersion;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.common.protocol.Errors.INVALID_REQUEST;
+import static org.apache.kafka.common.protocol.Errors.UNSUPPORTED_VERSION;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_EXACT;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_DEFAULT;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_SPECIFIED;
+
+
+/**
+ * Represents the client quotas in the metadata image.
+ *
+ * This class is thread-safe.
+ */
+public final class ClientQuotasImage {
+ public final static ClientQuotasImage EMPTY = new ClientQuotasImage(Collections.emptyMap());
+
+ private final Map<ClientQuotaEntity, ClientQuotaImage> entities;
+
+ public ClientQuotasImage(Map<ClientQuotaEntity, ClientQuotaImage> entities) {
+ this.entities = entities;
+ }
+
+ public boolean isEmpty() {
+ return entities.isEmpty();
+ }
+
+ Map<ClientQuotaEntity, ClientQuotaImage> entities() {
+ return entities;
+ }
+
+ public void write(Consumer<List<ApiMessageAndVersion>> out) throws IOException {
+ for (Entry<ClientQuotaEntity, ClientQuotaImage> entry : entities.entrySet()) {
+ ClientQuotaEntity entity = entry.getKey();
+ ClientQuotaImage clientQuotaImage = entry.getValue();
+ clientQuotaImage.write(entity, out);
+ }
+ }
+
+ public DescribeClientQuotasResponseData describe(DescribeClientQuotasRequestData request) {
+ DescribeClientQuotasResponseData response = new DescribeClientQuotasResponseData();
+ Map<String, String> exact = new HashMap<>();
+ Set<String> any = new HashSet<>();
+ for (DescribeClientQuotasRequestData.ComponentData component : request.components()) {
+ switch (component.matchType()) {
+ case MATCH_TYPE_EXACT:
+ if (component.match() == null) {
+ response.setErrorCode(INVALID_REQUEST.code());
+ response.setErrorMessage("Request specified MATCH_TYPE_EXACT, " +
+ "but set match string to null.");
+ return response;
+ }
+ exact.put(component.entityType(), component.match());
+ break;
+ case MATCH_TYPE_DEFAULT:
+ if (component.match() != null) {
+ response.setErrorCode(INVALID_REQUEST.code());
+ response.setErrorMessage("Request specified MATCH_TYPE_DEFAULT, " +
+ "but also specified a match string.");
+ return response;
+ }
+ exact.put(component.entityType(), null);
+ break;
+ case MATCH_TYPE_SPECIFIED:
+ if (component.match() != null) {
+ response.setErrorCode(INVALID_REQUEST.code());
+ response.setErrorMessage("Request specified MATCH_TYPE_SPECIFIED, " +
+ "but also specified a match string.");
+ return response;
+ }
+ any.add(component.entityType());
+ break;
+ default:
+ response.setErrorCode(UNSUPPORTED_VERSION.code());
+ response.setErrorMessage("Unknown match type " + component.matchType());
+ return response;
+ }
+ }
+ // TODO: this is O(N). We should do some indexing here to speed it up.
Review comment:
Is there any way to use the cache structures in ClientQuotaCache.scala?
##########
File path: metadata/src/main/java/org/apache/kafka/image/ClientQuotasImage.java
##########
@@ -0,0 +1,178 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.message.DescribeClientQuotasRequestData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData.EntityData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData.EntryData;
+import org.apache.kafka.common.quota.ClientQuotaEntity;
+import org.apache.kafka.server.common.ApiMessageAndVersion;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.common.protocol.Errors.INVALID_REQUEST;
+import static org.apache.kafka.common.protocol.Errors.UNSUPPORTED_VERSION;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_EXACT;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_DEFAULT;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_SPECIFIED;
+
+
+/**
+ * Represents the client quotas in the metadata image.
+ *
+ * This class is thread-safe.
+ */
+public final class ClientQuotasImage {
+ public final static ClientQuotasImage EMPTY = new ClientQuotasImage(Collections.emptyMap());
+
+ private final Map<ClientQuotaEntity, ClientQuotaImage> entities;
+
+ public ClientQuotasImage(Map<ClientQuotaEntity, ClientQuotaImage> entities) {
+ this.entities = entities;
+ }
+
+ public boolean isEmpty() {
+ return entities.isEmpty();
+ }
+
+ Map<ClientQuotaEntity, ClientQuotaImage> entities() {
+ return entities;
+ }
+
+ public void write(Consumer<List<ApiMessageAndVersion>> out) throws IOException {
+ for (Entry<ClientQuotaEntity, ClientQuotaImage> entry : entities.entrySet()) {
+ ClientQuotaEntity entity = entry.getKey();
+ ClientQuotaImage clientQuotaImage = entry.getValue();
+ clientQuotaImage.write(entity, out);
+ }
+ }
+
+ public DescribeClientQuotasResponseData describe(DescribeClientQuotasRequestData request) {
+ DescribeClientQuotasResponseData response = new DescribeClientQuotasResponseData();
+ Map<String, String> exact = new HashMap<>();
+ Set<String> any = new HashSet<>();
Review comment:
How about more explicit names like `exactMatch` and `typeMatch`?
##########
File path: metadata/src/main/java/org/apache/kafka/image/ClientQuotasImage.java
##########
@@ -0,0 +1,178 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.message.DescribeClientQuotasRequestData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData.EntityData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData.EntryData;
+import org.apache.kafka.common.quota.ClientQuotaEntity;
+import org.apache.kafka.server.common.ApiMessageAndVersion;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.common.protocol.Errors.INVALID_REQUEST;
+import static org.apache.kafka.common.protocol.Errors.UNSUPPORTED_VERSION;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_EXACT;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_DEFAULT;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_SPECIFIED;
+
+
+/**
+ * Represents the client quotas in the metadata image.
+ *
+ * This class is thread-safe.
+ */
+public final class ClientQuotasImage {
+ public final static ClientQuotasImage EMPTY = new ClientQuotasImage(Collections.emptyMap());
+
+ private final Map<ClientQuotaEntity, ClientQuotaImage> entities;
+
+ public ClientQuotasImage(Map<ClientQuotaEntity, ClientQuotaImage> entities) {
+ this.entities = entities;
+ }
+
+ public boolean isEmpty() {
+ return entities.isEmpty();
+ }
+
+ Map<ClientQuotaEntity, ClientQuotaImage> entities() {
+ return entities;
+ }
+
+ public void write(Consumer<List<ApiMessageAndVersion>> out) throws IOException {
+ for (Entry<ClientQuotaEntity, ClientQuotaImage> entry : entities.entrySet()) {
+ ClientQuotaEntity entity = entry.getKey();
+ ClientQuotaImage clientQuotaImage = entry.getValue();
+ clientQuotaImage.write(entity, out);
+ }
+ }
+
+ public DescribeClientQuotasResponseData describe(DescribeClientQuotasRequestData request) {
Review comment:
We previously would check for duplicates as well as empty entity types on the describe filter
##########
File path: core/src/main/scala/kafka/server/metadata/BrokerMetadataListener.scala
##########
@@ -70,230 +58,191 @@ class BrokerMetadataListener(
*/
@volatile private var _highestMetadataOffset = -1L
+ /**
+ * The current broker metadata image. Accessed only from the event queue thread.
+ */
+ private var _image = MetadataImage.EMPTY
+
+ /**
+ * The current metadata delta. Accessed only from the event queue thread.
+ */
+ private var _delta = new MetadataDelta(_image)
+
+ /**
+ * The object to use to publish new metadata changes, or None if this listener has not
+ * been activated yet.
+ */
+ private var _publisher: Option[MetadataPublisher] = None
+
+ /**
+ * The event queue which runs this listener.
+ */
val eventQueue = new KafkaEventQueue(time, logContext, threadNamePrefix.getOrElse(""))
+ /**
+ * Returns the highest metadata-offset. Thread-safe.
+ */
def highestMetadataOffset(): Long = _highestMetadataOffset
/**
* Handle new metadata records.
*/
- override def handleCommit(reader: BatchReader[ApiMessageAndVersion]): Unit = {
+ override def handleCommit(reader: BatchReader[ApiMessageAndVersion]): Unit =
eventQueue.append(new HandleCommitsEvent(reader))
+
+ class HandleCommitsEvent(reader: BatchReader[ApiMessageAndVersion])
+ extends EventQueue.FailureLoggingEvent(log) {
+ override def run(): Unit = {
+ val results = try {
+ val loadResults = loadBatches(_delta, reader)
+ if (isDebugEnabled) {
+ debug(s"Loaded new commits: ${loadResults}")
+ }
+ loadResults
+ } finally {
+ reader.close()
+ }
+ maybePublish(results.highestMetadataOffset)
+ }
}
/**
* Handle metadata snapshots
*/
- override def handleSnapshot(reader: SnapshotReader[ApiMessageAndVersion]): Unit = {
- // Loading snapshot on the broker is currently not supported.
- reader.close();
- throw new UnsupportedOperationException(s"Loading snapshot (${reader.snapshotId()}) is not supported")
- }
-
- // Visible for testing. It's useful to execute events synchronously in order
- // to make tests deterministic. This object is responsible for closing the reader.
- private[metadata] def execCommits(batchReader: BatchReader[ApiMessageAndVersion]): Unit = {
- new HandleCommitsEvent(batchReader).run()
- }
+ override def handleSnapshot(reader: SnapshotReader[ApiMessageAndVersion]): Unit =
+ eventQueue.append(new HandleSnapshotEvent(reader))
- class HandleCommitsEvent(
- reader: BatchReader[ApiMessageAndVersion]
- ) extends EventQueue.FailureLoggingEvent(log) {
+ class HandleSnapshotEvent(reader: SnapshotReader[ApiMessageAndVersion])
+ extends EventQueue.FailureLoggingEvent(log) {
override def run(): Unit = {
- try {
- while (reader.hasNext()) {
- apply(reader.next())
- }
+ val results = try {
+ info(s"Loading snapshot ${reader.snapshotId().offset}-${reader.snapshotId().epoch}.")
+ _delta = new MetadataDelta(_image) // Discard any previous deltas.
+ val loadResults = loadBatches(_delta, reader)
+ _delta.finishSnapshot()
+ info(s"Loaded snapshot ${reader.snapshotId().offset}-${reader.snapshotId().epoch}: " +
+ s"${loadResults}")
+ loadResults
} finally {
reader.close()
}
+ maybePublish(results.highestMetadataOffset)
}
+ }
- private def apply(batch: Batch[ApiMessageAndVersion]): Unit = {
- val records = batch.records
- val lastOffset = batch.lastOffset
+ case class BatchLoadResults(numBatches: Int,
+ numRecords: Int,
+ elapsedUs: Long,
+ highestMetadataOffset: Long) {
+ override def toString(): String = {
+ s"${numBatches} batch(es) with ${numRecords} record(s) ending at offset " +
+ s"${highestMetadataOffset} in ${elapsedUs} microseconds"
+ }
+ }
- if (isDebugEnabled) {
- debug(s"Metadata batch $lastOffset: handling ${records.size()} record(s).")
- }
- val imageBuilder =
- MetadataImageBuilder(brokerId, log, metadataCache.currentImage())
- val startNs = time.nanoseconds()
+ private def loadBatches(delta: MetadataDelta,
+ iterator: util.Iterator[Batch[ApiMessageAndVersion]]): BatchLoadResults = {
+ val startTimeNs = time.nanoseconds()
+ var numBatches = 0
+ var numRecords = 0
+ var newHighestMetadataOffset = _highestMetadataOffset
+ while (iterator.hasNext()) {
+ val batch = iterator.next()
var index = 0
- metadataBatchSizeHist.update(records.size())
- records.iterator().asScala.foreach { record =>
- try {
- if (isTraceEnabled) {
- trace("Metadata batch %d: processing [%d/%d]: %s.".format(lastOffset, index + 1,
- records.size(), record.toString))
- }
- handleMessage(imageBuilder, record.message, lastOffset)
- } catch {
- case e: Exception => error(s"Unable to handle record $index in batch " +
- s"ending at offset $lastOffset", e)
- }
- index = index + 1
- }
- if (imageBuilder.hasChanges) {
- val newImage = imageBuilder.build()
+ batch.records().forEach { messageAndVersion =>
+ newHighestMetadataOffset = batch.lastOffset()
if (isTraceEnabled) {
- trace(s"Metadata batch $lastOffset: creating new metadata image ${newImage}")
- } else if (isDebugEnabled) {
- debug(s"Metadata batch $lastOffset: creating new metadata image")
- }
- metadataCache.image(newImage)
- } else if (isDebugEnabled) {
- debug(s"Metadata batch $lastOffset: no new metadata image required.")
- }
- if (imageBuilder.hasPartitionChanges) {
- if (isDebugEnabled) {
- debug(s"Metadata batch $lastOffset: applying partition changes")
+ trace("Metadata batch %d: processing [%d/%d]: %s.".format(batch.lastOffset, index + 1,
+ batch.records().size(), messageAndVersion.message().toString()))
}
- replicaManager.handleMetadataRecords(imageBuilder, lastOffset,
- RequestHandlerHelper.onLeadershipChange(groupCoordinator, txnCoordinator, _, _))
- } else if (isDebugEnabled) {
- debug(s"Metadata batch $lastOffset: no partition changes found.")
+ delta.replay(messageAndVersion.message())
+ numRecords += 1
+ index += 1
}
- _highestMetadataOffset = lastOffset
- val endNs = time.nanoseconds()
- val deltaUs = TimeUnit.MICROSECONDS.convert(endNs - startNs, TimeUnit.NANOSECONDS)
- debug(s"Metadata batch $lastOffset: advanced highest metadata offset in ${deltaUs} " +
- "microseconds.")
- batchProcessingTimeHist.update(deltaUs)
+ metadataBatchSizeHist.update(batch.records().size())
+ numBatches = numBatches + 1
}
+ _highestMetadataOffset = newHighestMetadataOffset
+ val endTimeNs = time.nanoseconds()
+ val elapsedUs = TimeUnit.MICROSECONDS.convert(endTimeNs - startTimeNs, TimeUnit.NANOSECONDS)
+ batchProcessingTimeHist.update(elapsedUs)
+ BatchLoadResults(numBatches, numRecords, elapsedUs, newHighestMetadataOffset)
}
- private def handleMessage(imageBuilder: MetadataImageBuilder,
- record: ApiMessage,
- lastOffset: Long): Unit = {
- val recordType = try {
- fromId(record.apiKey())
- } catch {
- case e: Exception => throw new RuntimeException("Unknown metadata record type " +
- s"${record.apiKey()} in batch ending at offset ${lastOffset}.")
- }
-
- record match {
- case rec: RegisterBrokerRecord => handleRegisterBrokerRecord(imageBuilder, rec)
- case rec: UnregisterBrokerRecord => handleUnregisterBrokerRecord(imageBuilder, rec)
- case rec: FenceBrokerRecord => handleFenceBrokerRecord(imageBuilder, rec)
- case rec: UnfenceBrokerRecord => handleUnfenceBrokerRecord(imageBuilder, rec)
- case rec: TopicRecord => handleTopicRecord(imageBuilder, rec)
- case rec: PartitionRecord => handlePartitionRecord(imageBuilder, rec)
- case rec: PartitionChangeRecord => handlePartitionChangeRecord(imageBuilder, rec)
- case rec: RemoveTopicRecord => handleRemoveTopicRecord(imageBuilder, rec)
- case rec: ConfigRecord => handleConfigRecord(rec)
- case rec: ClientQuotaRecord => handleClientQuotaRecord(imageBuilder, rec)
- case rec: ProducerIdsRecord => handleProducerIdRecord(rec)
- case _ => throw new RuntimeException(s"Unhandled record $record with type $recordType")
- }
+ def startPublishing(publisher: MetadataPublisher): CompletableFuture[Void] = {
+ val event = new StartPublishingEvent(publisher)
+ eventQueue.append(event)
+ event.future
}
- def handleRegisterBrokerRecord(imageBuilder: MetadataImageBuilder,
- record: RegisterBrokerRecord): Unit = {
- val broker = MetadataBroker(record)
- imageBuilder.brokersBuilder().add(broker)
- }
-
- def handleUnregisterBrokerRecord(imageBuilder: MetadataImageBuilder,
- record: UnregisterBrokerRecord): Unit = {
- imageBuilder.brokersBuilder().remove(record.brokerId())
- }
-
- def handleTopicRecord(imageBuilder: MetadataImageBuilder,
- record: TopicRecord): Unit = {
- imageBuilder.partitionsBuilder().addUuidMapping(record.name(), record.topicId())
- }
+ class StartPublishingEvent(publisher: MetadataPublisher)
+ extends EventQueue.FailureLoggingEvent(log) {
+ val future = new CompletableFuture[Void]()
- def handlePartitionRecord(imageBuilder: MetadataImageBuilder,
- record: PartitionRecord): Unit = {
- imageBuilder.topicIdToName(record.topicId()) match {
- case None => throw new RuntimeException(s"Unable to locate topic with ID ${record.topicId}")
- case Some(name) =>
- val partition = MetadataPartition(name, record)
- imageBuilder.partitionsBuilder().set(partition)
+ override def run(): Unit = {
+ _publisher = Some(publisher)
+ log.info(s"Starting to publish metadata events at offset ${_highestMetadataOffset}.")
+ try {
+ maybePublish(_highestMetadataOffset)
+ future.complete(null)
+ } catch {
+ case e: Throwable => future.completeExceptionally(e)
+ }
}
}
- def handleConfigRecord(record: ConfigRecord): Unit = {
- val t = ConfigResource.Type.forId(record.resourceType())
- if (t == ConfigResource.Type.UNKNOWN) {
- throw new RuntimeException("Unable to understand config resource type " +
- s"${Integer.valueOf(record.resourceType())}")
+ private def maybePublish(newHighestMetadataOffset: Long): Unit = {
+ _publisher match {
+ case None => // Nothing to do
+ case Some(publisher) => {
+ val delta = _delta
+ _image = _delta.apply()
+ _delta = new MetadataDelta(_image)
+ publisher.publish(newHighestMetadataOffset, delta, _image)
+ }
}
- val resource = new ConfigResource(t, record.resourceName())
- configRepository.setConfig(resource, record.name(), record.value())
- }
-
- def handlePartitionChangeRecord(imageBuilder: MetadataImageBuilder,
- record: PartitionChangeRecord): Unit = {
- imageBuilder.partitionsBuilder().handleChange(record)
}
- def handleFenceBrokerRecord(imageBuilder: MetadataImageBuilder,
- record: FenceBrokerRecord): Unit = {
- // TODO: add broker epoch to metadata cache, and check it here.
- imageBuilder.brokersBuilder().changeFencing(record.id(), fenced = true)
+ override def handleLeaderChange(leaderAndEpoch: LeaderAndEpoch): Unit = {
+ // TODO: cache leaderAndEpoch so we can use the epoch in broker-initiated snapshots.
}
- def handleUnfenceBrokerRecord(imageBuilder: MetadataImageBuilder,
- record: UnfenceBrokerRecord): Unit = {
- // TODO: add broker epoch to metadata cache, and check it here.
- imageBuilder.brokersBuilder().changeFencing(record.id(), fenced = false)
+ override def beginShutdown(): Unit = {
+ eventQueue.beginShutdown("beginShutdown", new ShutdownEvent())
}
- def handleRemoveTopicRecord(imageBuilder: MetadataImageBuilder,
- record: RemoveTopicRecord): Unit = {
- imageBuilder.topicIdToName(record.topicId()) match {
- case None =>
- throw new RuntimeException(s"Unable to locate topic with ID ${record.topicId}")
-
- case Some(topicName) =>
- info(s"Processing deletion of topic $topicName with id ${record.topicId}")
- val removedPartitions = imageBuilder.partitionsBuilder().removeTopicById(record.topicId())
- groupCoordinator.handleDeletedPartitions(removedPartitions.map(_.toTopicPartition).toSeq, RequestLocal.NoCaching)
- configRepository.remove(new ConfigResource(ConfigResource.Type.TOPIC, topicName))
+ class ShutdownEvent() extends EventQueue.FailureLoggingEvent(log) {
+ override def run(): Unit = {
+ removeMetric(BrokerMetadataListener.MetadataBatchProcessingTimeUs)
+ removeMetric(BrokerMetadataListener.MetadataBatchSizes)
}
}
- def handleClientQuotaRecord(imageBuilder: MetadataImageBuilder,
- record: ClientQuotaRecord): Unit = {
- // TODO add quotas to MetadataImageBuilder
- clientQuotaManager.handleQuotaRecord(record)
+ def close(): Unit = {
+ beginShutdown()
+ eventQueue.close()
}
- def handleProducerIdRecord(record: ProducerIdsRecord): Unit = {
- // This is a no-op since brokers get their producer ID blocks directly from the controller via
- // AllocateProducerIds RPC response
+ // VisibleForTesting
+ private[kafka] def getImageRecords(): CompletableFuture[util.List[ApiMessageAndVersion]] = {
+ val future = new CompletableFuture[util.List[ApiMessageAndVersion]]()
+ eventQueue.append(new GetImageRecordsEvent(future))
+ future
}
- class HandleNewLeaderEvent(leaderAndEpoch: LeaderAndEpoch)
- extends EventQueue.FailureLoggingEvent(log) {
- override def run(): Unit = {
- val imageBuilder =
- MetadataImageBuilder(brokerId, log, metadataCache.currentImage())
- imageBuilder.controllerId(leaderAndEpoch.leaderId.asScala)
- metadataCache.image(imageBuilder.build())
+ class GetImageRecordsEvent(future: CompletableFuture[util.List[ApiMessageAndVersion]])
+ extends EventQueue.FailureLoggingEvent(log) with Consumer[util.List[ApiMessageAndVersion]] {
+ val records = new util.ArrayList[ApiMessageAndVersion]()
+ override def accept(batch: util.List[ApiMessageAndVersion]): Unit = {
+ if (batch == null) {
Review comment:
Why use the `null` here to finalize the image? Could we complete the future below where we call `_image.write`?
Alternatively, we could use a composite Consumer + Closable type so MetadataImage could call `close` instead of `out.accept(null)`.
--
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] hachikuji edited a comment on pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
hachikuji edited a comment on pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#issuecomment-873632735
@cmccabe The following test cases in `ClientQuotasRequestTest` that fail consistently:
- `testDescribeClientQuotasMatchPartial`
- `testClientQuotasUnsupportedEntityTypes`
- `testDescribeClientQuotasMatchExact`
I checked on trunk and they are all passing.
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663271148
##########
File path: core/src/main/scala/kafka/server/FinalizedFeatureCache.scala
##########
@@ -127,6 +131,22 @@ class FinalizedFeatureCache(private val brokerFeatures: BrokerFeatures) extends
}
}
+ def update(featuresDelta: FeaturesDelta, highestMetadataOffset: Long): Unit = {
+ val features = featuresAndEpoch.getOrElse(
+ FinalizedFeaturesAndEpoch(Features.emptyFinalizedFeatures(), -1))
+ val newFeatures = new util.HashMap[String, FinalizedVersionRange]()
+ newFeatures.putAll(features.features.features())
Review comment:
Yes, the features code needs a refactor. I guess when we do kraft upgrade we'll fix it up.
--
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] hachikuji commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
hachikuji commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r661670006
##########
File path: core/src/main/scala/kafka/server/BrokerServer.scala
##########
@@ -264,19 +266,13 @@ class BrokerServer(
/* Add all reconfigurables for config change notification before starting the metadata listener */
config.dynamicConfig.addReconfigurables(this)
- val clientQuotaMetadataManager = new ClientQuotaMetadataManager(
- quotaManagers, socketServer.connectionQuotas, quotaCache)
+ // TODO : check that we're properly handling "ConfigType" Client, User, and Ip (which are not
Review comment:
Do you want to finish this or should we file a jira?
##########
File path: clients/src/main/java/org/apache/kafka/common/requests/DescribeClientQuotasResponse.java
##########
@@ -84,6 +84,7 @@ public static DescribeClientQuotasResponse parse(ByteBuffer buffer, short versio
return new DescribeClientQuotasResponse(new DescribeClientQuotasResponseData(new ByteBufferAccessor(buffer), version));
}
+ // TODO: remove this function
Review comment:
Do you want to do this?
##########
File path: core/src/main/scala/kafka/server/MetadataCache.scala
##########
@@ -96,7 +87,7 @@ object MetadataCache {
new ZkMetadataCache(brokerId)
}
- def raftMetadataCache(brokerId: Int): RaftMetadataCache = {
- new RaftMetadataCache(brokerId)
+ def raftMetadataCache(brokerId: Int): KRaftMetadataCache = {
Review comment:
nit: perhaps we may as well change the name to `kraftMetadataCache` as well
##########
File path: core/src/main/scala/kafka/server/ReplicaManager.scala
##########
@@ -1302,7 +1278,8 @@ class ReplicaManager(val config: KafkaConfig,
stateChangeLogger.warn(stateControllerEpochErrorMessage)
throw new ControllerMovedException(stateChangeLogger.messageWithPrefix(stateControllerEpochErrorMessage))
} else {
- val deletedPartitions = metadataCache.updateMetadata(correlationId, updateMetadataRequest)
+ val zkMetadataCache = metadataCache.asInstanceOf[ZkMetadataCache]
Review comment:
Could we use `MetadataSupport` in `ReplicaManager`?
##########
File path: core/src/main/scala/kafka/server/ConfigHandler.scala
##########
@@ -51,7 +51,8 @@ trait ConfigHandler {
* The TopicConfigHandler will process topic config changes in ZK.
* The callback provides the topic name and the full properties set read from ZK
*/
-class TopicConfigHandler(private val logManager: LogManager, kafkaConfig: KafkaConfig, val quotas: QuotaManagers, kafkaController: KafkaController) extends ConfigHandler with Logging {
+class TopicConfigHandler(private val logManager: LogManager, kafkaConfig: KafkaConfig,
Review comment:
nit: can we generalize the doc above to cover events from the metadata log?
##########
File path: core/src/main/scala/kafka/server/metadata/KRaftMetadataCache.scala
##########
@@ -0,0 +1,354 @@
+/*
+ * 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.metadata
+
+import kafka.controller.StateChangeLogger
+import kafka.server.MetadataCache
+import kafka.utils.Logging
+import org.apache.kafka.common.internals.Topic
+import org.apache.kafka.common.message.MetadataResponseData.{MetadataResponsePartition, MetadataResponseTopic}
+import org.apache.kafka.common.{Cluster, Node, PartitionInfo, TopicPartition, Uuid}
+import org.apache.kafka.common.message.UpdateMetadataRequestData.UpdateMetadataPartitionState
+import org.apache.kafka.common.network.ListenerName
+import org.apache.kafka.common.protocol.Errors
+import org.apache.kafka.common.requests.MetadataResponse
+import org.apache.kafka.image.MetadataImage
+import java.util
+import java.util.{Collections, Properties}
+import java.util.concurrent.ThreadLocalRandom
+
+import kafka.admin.BrokerMetadata
+import org.apache.kafka.common.config.ConfigResource
+import org.apache.kafka.common.message.{DescribeClientQuotasRequestData, DescribeClientQuotasResponseData}
+import org.apache.kafka.metadata.{PartitionRegistration, Replicas}
+
+import scala.collection.{Seq, Set, mutable}
+import scala.jdk.CollectionConverters._
+import scala.compat.java8.OptionConverters._
+
+
+class KRaftMetadataCache(val brokerId: Int) extends MetadataCache with Logging with ConfigRepository {
+ this.logIdent = s"[MetadataCache brokerId=$brokerId] "
+
+ // This is the cache state. Every MetadataImage instance is immutable, and updates
+ // replace this value with a completely new one. This means reads (which are not under
+ // any lock) need to grab the value of this variable once, and retain that read copy for
+ // the /duration of their operation. Multiple reads of this value risk getting different
Review comment:
nit: drop slash before duration
##########
File path: core/src/main/scala/kafka/server/BrokerServer.scala
##########
@@ -331,46 +327,40 @@ class BrokerServer(
new FetchSessionCache(config.maxIncrementalFetchSessionCacheSlots,
KafkaServer.MIN_INCREMENTAL_FETCH_SESSION_EVICTION_MS))
- // Start processing requests once we've caught up on the metadata log, recovered logs if necessary,
- // and started all services that we previously delayed starting.
- val raftSupport = RaftSupport(forwardingManager, metadataCache, quotaCache)
+ // Create the request processor objects.
+ val raftSupport = RaftSupport(forwardingManager, metadataCache)
dataPlaneRequestProcessor = new KafkaApis(socketServer.dataPlaneRequestChannel, raftSupport,
replicaManager, groupCoordinator, transactionCoordinator, autoTopicCreationManager,
- config.nodeId, config, configRepository, metadataCache, metrics, authorizer, quotaManagers,
+ config.nodeId, config, metadataCache, metadataCache, metrics, authorizer, quotaManagers,
fetchManager, brokerTopicStats, clusterId, time, tokenManager, apiVersionManager)
- dataPlaneRequestHandlerPool = new KafkaRequestHandlerPool(config.nodeId, socketServer.dataPlaneRequestChannel, dataPlaneRequestProcessor, time,
- config.numIoThreads, s"${SocketServer.DataPlaneMetricPrefix}RequestHandlerAvgIdlePercent", SocketServer.DataPlaneThreadPrefix)
-
- socketServer.controlPlaneRequestChannelOpt.foreach { controlPlaneRequestChannel =>
- controlPlaneRequestProcessor = new KafkaApis(controlPlaneRequestChannel, raftSupport,
- replicaManager, groupCoordinator, transactionCoordinator, autoTopicCreationManager,
- config.nodeId, config, configRepository, metadataCache, metrics, authorizer, quotaManagers,
- fetchManager, brokerTopicStats, clusterId, time, tokenManager, apiVersionManager)
+ dataPlaneRequestHandlerPool = new KafkaRequestHandlerPool(config.nodeId,
+ socketServer.dataPlaneRequestChannel, dataPlaneRequestProcessor, time,
+ config.numIoThreads, s"${SocketServer.DataPlaneMetricPrefix}RequestHandlerAvgIdlePercent",
+ SocketServer.DataPlaneThreadPrefix)
- controlPlaneRequestHandlerPool = new KafkaRequestHandlerPool(config.nodeId, socketServer.controlPlaneRequestChannelOpt.get, controlPlaneRequestProcessor, time,
- 1, s"${SocketServer.ControlPlaneMetricPrefix}RequestHandlerAvgIdlePercent", SocketServer.ControlPlaneThreadPrefix)
+ if (socketServer.controlPlaneRequestChannelOpt.isDefined) {
+ throw new RuntimeException("KIP-291 endpoints are not supported when in KRaft mode.")
Review comment:
nit: It would be better to refer to the configuration. No one will know what KIP-291 is.
##########
File path: core/src/main/scala/kafka/server/metadata/BrokerMetadataPublisher.scala
##########
@@ -0,0 +1,249 @@
+/**
+ * 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.metadata
+
+import kafka.coordinator.group.GroupCoordinator
+import kafka.coordinator.transaction.TransactionCoordinator
+import kafka.log.{Log, LogManager}
+import kafka.server.ConfigType
+import kafka.server.{ConfigHandler, FinalizedFeatureCache, KafkaConfig, ReplicaManager, RequestLocal}
+import kafka.utils.Logging
+import org.apache.kafka.common.TopicPartition
+import org.apache.kafka.common.config.ConfigResource
+import org.apache.kafka.common.internals.Topic
+import org.apache.kafka.image.{MetadataDelta, MetadataImage, TopicDelta}
+
+import scala.collection.mutable
+
+
+object BrokerMetadataPublisher {
+ /**
+ * Given a topic name, find out if it changed. Note: if a topic named X was deleted and
+ * then re-created, this method will return just the re-creation. The deletion will show
+ * up in deletedTopicIds and must be handled separately.
+ *
+ * @param topicName The topic name.
+ * @param newImage The new metadata image.
+ * @param delta The metadata delta to search.
+ *
+ * @return The delta, or None if appropriate.
+ */
+ def getTopicDelta(topicName: String,
+ newImage: MetadataImage,
+ delta: MetadataDelta): Option[TopicDelta] = {
+ Option(newImage.topics().getTopic(topicName)).map {
+ topicImage => delta.topicsDelta().changedTopic(topicImage.id())
+ }
+ }
+
+ /**
+ * Find logs which should not be on the current broker, according to the metadata image.
+ *
+ * @param brokerId The ID of the current broker.
+ * @param newImage The metadata image.
+ * @param logs A collection of Log objects.
+ *
+ * @return The topic partitions which are no longer needed on this broker.
+ */
+ def findGhostReplicas(brokerId: Int,
+ newImage: MetadataImage,
+ logs: Iterable[Log]): Iterable[TopicPartition] = {
+ logs.flatMap { log =>
+ log.topicId match {
+ case None => throw new RuntimeException(s"Topic ${log.name} does not have a topic ID, " +
+ "which is not allowed when running in KRaft mode.")
+ case Some(topicId) =>
+ val partitionId = log.topicPartition.partition()
+ Option(newImage.topics().getPartition(topicId, partitionId)) match {
+ case None => None
+ case Some(partition) => if (partition.replicas.contains(brokerId)) {
+ Some(log.topicPartition)
+ } else {
+ None
+ }
+ }
+ }
+ }
+ }
+}
+
+class BrokerMetadataPublisher(conf: KafkaConfig,
+ metadataCache: KRaftMetadataCache,
+ logManager: LogManager,
+ replicaManager: ReplicaManager,
+ groupCoordinator: GroupCoordinator,
+ txnCoordinator: TransactionCoordinator,
+ clientQuotaMetadataManager: ClientQuotaMetadataManager,
+ featureCache: FinalizedFeatureCache,
+ dynamicConfigHandlers: Map[String, ConfigHandler]) extends MetadataPublisher with Logging {
+ logIdent = s"[BrokerMetadataPublisher id=${conf.nodeId}] "
+
+ import BrokerMetadataPublisher._
+
+ /**
+ * The broker ID.
+ */
+ val brokerId = conf.nodeId
+
+ /**
+ * True if this is the first time we have published metadata.
+ */
+ var _firstPublish = false
+
+ override def publish(newHighestMetadataOffset: Long,
+ delta: MetadataDelta,
+ newImage: MetadataImage): Unit = {
+ try {
+ // Publish the new metadata image to the metadata cache.
+ metadataCache.setImage(newImage)
+
+ if (_firstPublish) {
+ info(s"Publishing initial metadata at offset ${newHighestMetadataOffset}.")
+
+ // If this is the first metadata update we are applying, initialize the managers
+ // first (but after setting up the metadata cache).
+ initializeManagers()
+ } else if (isDebugEnabled) {
+ debug(s"Publishing metadata at offset ${newHighestMetadataOffset}.")
+ }
+
+ // Apply feature deltas.
+ Option(delta.featuresDelta()).foreach { featuresDelta =>
+ featureCache.update(featuresDelta, newHighestMetadataOffset)
+ }
+
+ // Apply topic deltas.
+ Option(delta.topicsDelta()).foreach { topicsDelta =>
+ // Notify the replica manager about changes to topics.
+ replicaManager.applyDelta(newImage, topicsDelta)
+
+ // Handle the case where the old consumer offsets topic was deleted.
+ if (topicsDelta.topicWasDeleted(Topic.GROUP_METADATA_TOPIC_NAME)) {
+ topicsDelta.image().getTopic(Topic.GROUP_METADATA_TOPIC_NAME).partitions().entrySet().forEach {
+ entry =>
+ if (entry.getValue().leader == brokerId) {
+ groupCoordinator.onResignation(entry.getKey(), Some(entry.getValue().leaderEpoch))
+ }
+ }
+ }
+ // Handle the case where we have new local leaders or followers for the consumer
+ // offsets topic.
+ getTopicDelta(Topic.GROUP_METADATA_TOPIC_NAME, newImage, delta).foreach { topicDelta =>
+ topicDelta.newLocalLeaders(brokerId).forEach {
+ entry => groupCoordinator.onElection(entry.getKey(), entry.getValue().leaderEpoch)
+ }
+ topicDelta.newLocalFollowers(brokerId).forEach {
+ entry => groupCoordinator.onResignation(entry.getKey(), Some(entry.getValue().leaderEpoch))
+ }
+ }
+
+ // Handle the case where the old transaction state topic was deleted.
+ if (topicsDelta.topicWasDeleted(Topic.TRANSACTION_STATE_TOPIC_NAME)) {
+ topicsDelta.image().getTopic(Topic.TRANSACTION_STATE_TOPIC_NAME).partitions().entrySet().forEach {
+ entry =>
+ if (entry.getValue().leader == brokerId) {
+ txnCoordinator.onResignation(entry.getKey(), Some(entry.getValue().leaderEpoch))
+ }
+ }
+ }
+ // If the transaction state topic changed in a way that's relevant to this broker,
+ // notify the transaction coordinator.
+ getTopicDelta(Topic.TRANSACTION_STATE_TOPIC_NAME, newImage, delta).foreach { topicDelta =>
+ topicDelta.newLocalLeaders(brokerId).forEach {
+ entry => txnCoordinator.onElection(entry.getKey(), entry.getValue().leaderEpoch)
+ }
+ topicDelta.newLocalFollowers(brokerId).forEach {
+ entry => txnCoordinator.onResignation(entry.getKey(), Some(entry.getValue().leaderEpoch))
+ }
+ }
+
+ // Notify the group coordinator about deleted topics.
+ val deletedTopicPartitions = new mutable.ArrayBuffer[TopicPartition]()
+ topicsDelta.deletedTopicIds().forEach { id =>
+ val topicImage = topicsDelta.image().getTopic(id)
+ topicImage.partitions().keySet().forEach {
+ id => deletedTopicPartitions += new TopicPartition(topicImage.name(), id)
+ }
+ }
+ if (!deletedTopicPartitions.isEmpty) {
Review comment:
nit: use nonEmpty
##########
File path: core/src/main/scala/kafka/server/metadata/BrokerMetadataPublisher.scala
##########
@@ -0,0 +1,249 @@
+/**
+ * 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.metadata
+
+import kafka.coordinator.group.GroupCoordinator
+import kafka.coordinator.transaction.TransactionCoordinator
+import kafka.log.{Log, LogManager}
+import kafka.server.ConfigType
+import kafka.server.{ConfigHandler, FinalizedFeatureCache, KafkaConfig, ReplicaManager, RequestLocal}
+import kafka.utils.Logging
+import org.apache.kafka.common.TopicPartition
+import org.apache.kafka.common.config.ConfigResource
+import org.apache.kafka.common.internals.Topic
+import org.apache.kafka.image.{MetadataDelta, MetadataImage, TopicDelta}
+
+import scala.collection.mutable
+
+
+object BrokerMetadataPublisher {
+ /**
+ * Given a topic name, find out if it changed. Note: if a topic named X was deleted and
+ * then re-created, this method will return just the re-creation. The deletion will show
+ * up in deletedTopicIds and must be handled separately.
+ *
+ * @param topicName The topic name.
+ * @param newImage The new metadata image.
+ * @param delta The metadata delta to search.
+ *
+ * @return The delta, or None if appropriate.
+ */
+ def getTopicDelta(topicName: String,
+ newImage: MetadataImage,
+ delta: MetadataDelta): Option[TopicDelta] = {
+ Option(newImage.topics().getTopic(topicName)).map {
+ topicImage => delta.topicsDelta().changedTopic(topicImage.id())
+ }
+ }
+
+ /**
+ * Find logs which should not be on the current broker, according to the metadata image.
+ *
+ * @param brokerId The ID of the current broker.
+ * @param newImage The metadata image.
+ * @param logs A collection of Log objects.
+ *
+ * @return The topic partitions which are no longer needed on this broker.
+ */
+ def findGhostReplicas(brokerId: Int,
+ newImage: MetadataImage,
+ logs: Iterable[Log]): Iterable[TopicPartition] = {
+ logs.flatMap { log =>
+ log.topicId match {
+ case None => throw new RuntimeException(s"Topic ${log.name} does not have a topic ID, " +
+ "which is not allowed when running in KRaft mode.")
+ case Some(topicId) =>
+ val partitionId = log.topicPartition.partition()
+ Option(newImage.topics().getPartition(topicId, partitionId)) match {
+ case None => None
+ case Some(partition) => if (partition.replicas.contains(brokerId)) {
+ Some(log.topicPartition)
+ } else {
+ None
+ }
+ }
+ }
+ }
+ }
+}
+
+class BrokerMetadataPublisher(conf: KafkaConfig,
+ metadataCache: KRaftMetadataCache,
+ logManager: LogManager,
+ replicaManager: ReplicaManager,
+ groupCoordinator: GroupCoordinator,
+ txnCoordinator: TransactionCoordinator,
+ clientQuotaMetadataManager: ClientQuotaMetadataManager,
+ featureCache: FinalizedFeatureCache,
+ dynamicConfigHandlers: Map[String, ConfigHandler]) extends MetadataPublisher with Logging {
+ logIdent = s"[BrokerMetadataPublisher id=${conf.nodeId}] "
+
+ import BrokerMetadataPublisher._
+
+ /**
+ * The broker ID.
+ */
+ val brokerId = conf.nodeId
+
+ /**
+ * True if this is the first time we have published metadata.
+ */
+ var _firstPublish = false
Review comment:
Do you mean to initialize this to `true`? Otherwise it is always false.
##########
File path: core/src/main/scala/kafka/server/BrokerServer.scala
##########
@@ -31,9 +31,9 @@ import kafka.metrics.KafkaYammerMetrics
import kafka.network.SocketServer
import kafka.raft.RaftManager
import kafka.security.CredentialProvider
-import kafka.server.metadata.{BrokerMetadataListener, CachedConfigRepository, ClientQuotaCache, ClientQuotaMetadataManager, RaftMetadataCache}
+import kafka.server.metadata.{BrokerMetadataListener, BrokerMetadataPublisher, ClientQuotaMetadataManager, KRaftMetadataCache}
import kafka.utils.{CoreUtils, KafkaScheduler}
-import org.apache.kafka.common.internals.Topic.{GROUP_METADATA_TOPIC_NAME, TRANSACTION_STATE_TOPIC_NAME}
+//import org.apache.kafka.common.internals.Topic.{GROUP_METADATA_TOPIC_NAME, TRANSACTION_STATE_TOPIC_NAME}
Review comment:
nit: remove this?
##########
File path: core/src/main/scala/kafka/server/FinalizedFeatureCache.scala
##########
@@ -127,6 +131,22 @@ class FinalizedFeatureCache(private val brokerFeatures: BrokerFeatures) extends
}
}
+ def update(featuresDelta: FeaturesDelta, highestMetadataOffset: Long): Unit = {
+ val features = featuresAndEpoch.getOrElse(
+ FinalizedFeaturesAndEpoch(Features.emptyFinalizedFeatures(), -1))
+ val newFeatures = new util.HashMap[String, FinalizedVersionRange]()
+ newFeatures.putAll(features.features.features())
Review comment:
features.features.features eh?
##########
File path: core/src/main/scala/kafka/server/metadata/BrokerMetadataPublisher.scala
##########
@@ -0,0 +1,249 @@
+/**
+ * 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.metadata
+
+import kafka.coordinator.group.GroupCoordinator
+import kafka.coordinator.transaction.TransactionCoordinator
+import kafka.log.{Log, LogManager}
+import kafka.server.ConfigType
+import kafka.server.{ConfigHandler, FinalizedFeatureCache, KafkaConfig, ReplicaManager, RequestLocal}
+import kafka.utils.Logging
+import org.apache.kafka.common.TopicPartition
+import org.apache.kafka.common.config.ConfigResource
+import org.apache.kafka.common.internals.Topic
+import org.apache.kafka.image.{MetadataDelta, MetadataImage, TopicDelta}
+
+import scala.collection.mutable
+
+
+object BrokerMetadataPublisher {
+ /**
+ * Given a topic name, find out if it changed. Note: if a topic named X was deleted and
+ * then re-created, this method will return just the re-creation. The deletion will show
+ * up in deletedTopicIds and must be handled separately.
+ *
+ * @param topicName The topic name.
+ * @param newImage The new metadata image.
+ * @param delta The metadata delta to search.
+ *
+ * @return The delta, or None if appropriate.
+ */
+ def getTopicDelta(topicName: String,
+ newImage: MetadataImage,
+ delta: MetadataDelta): Option[TopicDelta] = {
+ Option(newImage.topics().getTopic(topicName)).map {
+ topicImage => delta.topicsDelta().changedTopic(topicImage.id())
+ }
+ }
+
+ /**
+ * Find logs which should not be on the current broker, according to the metadata image.
+ *
+ * @param brokerId The ID of the current broker.
+ * @param newImage The metadata image.
+ * @param logs A collection of Log objects.
+ *
+ * @return The topic partitions which are no longer needed on this broker.
+ */
+ def findGhostReplicas(brokerId: Int,
+ newImage: MetadataImage,
+ logs: Iterable[Log]): Iterable[TopicPartition] = {
+ logs.flatMap { log =>
+ log.topicId match {
+ case None => throw new RuntimeException(s"Topic ${log.name} does not have a topic ID, " +
+ "which is not allowed when running in KRaft mode.")
+ case Some(topicId) =>
+ val partitionId = log.topicPartition.partition()
+ Option(newImage.topics().getPartition(topicId, partitionId)) match {
+ case None => None
+ case Some(partition) => if (partition.replicas.contains(brokerId)) {
+ Some(log.topicPartition)
+ } else {
+ None
+ }
+ }
+ }
+ }
+ }
+}
+
+class BrokerMetadataPublisher(conf: KafkaConfig,
+ metadataCache: KRaftMetadataCache,
+ logManager: LogManager,
+ replicaManager: ReplicaManager,
+ groupCoordinator: GroupCoordinator,
+ txnCoordinator: TransactionCoordinator,
+ clientQuotaMetadataManager: ClientQuotaMetadataManager,
+ featureCache: FinalizedFeatureCache,
+ dynamicConfigHandlers: Map[String, ConfigHandler]) extends MetadataPublisher with Logging {
+ logIdent = s"[BrokerMetadataPublisher id=${conf.nodeId}] "
+
+ import BrokerMetadataPublisher._
+
+ /**
+ * The broker ID.
+ */
+ val brokerId = conf.nodeId
+
+ /**
+ * True if this is the first time we have published metadata.
+ */
+ var _firstPublish = false
+
+ override def publish(newHighestMetadataOffset: Long,
+ delta: MetadataDelta,
+ newImage: MetadataImage): Unit = {
+ try {
+ // Publish the new metadata image to the metadata cache.
+ metadataCache.setImage(newImage)
+
+ if (_firstPublish) {
+ info(s"Publishing initial metadata at offset ${newHighestMetadataOffset}.")
+
+ // If this is the first metadata update we are applying, initialize the managers
+ // first (but after setting up the metadata cache).
+ initializeManagers()
+ } else if (isDebugEnabled) {
+ debug(s"Publishing metadata at offset ${newHighestMetadataOffset}.")
+ }
+
+ // Apply feature deltas.
+ Option(delta.featuresDelta()).foreach { featuresDelta =>
+ featureCache.update(featuresDelta, newHighestMetadataOffset)
+ }
+
+ // Apply topic deltas.
+ Option(delta.topicsDelta()).foreach { topicsDelta =>
+ // Notify the replica manager about changes to topics.
+ replicaManager.applyDelta(newImage, topicsDelta)
+
+ // Handle the case where the old consumer offsets topic was deleted.
+ if (topicsDelta.topicWasDeleted(Topic.GROUP_METADATA_TOPIC_NAME)) {
+ topicsDelta.image().getTopic(Topic.GROUP_METADATA_TOPIC_NAME).partitions().entrySet().forEach {
+ entry =>
+ if (entry.getValue().leader == brokerId) {
+ groupCoordinator.onResignation(entry.getKey(), Some(entry.getValue().leaderEpoch))
+ }
+ }
+ }
+ // Handle the case where we have new local leaders or followers for the consumer
+ // offsets topic.
+ getTopicDelta(Topic.GROUP_METADATA_TOPIC_NAME, newImage, delta).foreach { topicDelta =>
+ topicDelta.newLocalLeaders(brokerId).forEach {
+ entry => groupCoordinator.onElection(entry.getKey(), entry.getValue().leaderEpoch)
+ }
+ topicDelta.newLocalFollowers(brokerId).forEach {
+ entry => groupCoordinator.onResignation(entry.getKey(), Some(entry.getValue().leaderEpoch))
+ }
+ }
+
+ // Handle the case where the old transaction state topic was deleted.
+ if (topicsDelta.topicWasDeleted(Topic.TRANSACTION_STATE_TOPIC_NAME)) {
+ topicsDelta.image().getTopic(Topic.TRANSACTION_STATE_TOPIC_NAME).partitions().entrySet().forEach {
+ entry =>
+ if (entry.getValue().leader == brokerId) {
+ txnCoordinator.onResignation(entry.getKey(), Some(entry.getValue().leaderEpoch))
+ }
+ }
+ }
+ // If the transaction state topic changed in a way that's relevant to this broker,
+ // notify the transaction coordinator.
+ getTopicDelta(Topic.TRANSACTION_STATE_TOPIC_NAME, newImage, delta).foreach { topicDelta =>
+ topicDelta.newLocalLeaders(brokerId).forEach {
+ entry => txnCoordinator.onElection(entry.getKey(), entry.getValue().leaderEpoch)
+ }
+ topicDelta.newLocalFollowers(brokerId).forEach {
+ entry => txnCoordinator.onResignation(entry.getKey(), Some(entry.getValue().leaderEpoch))
+ }
+ }
+
+ // Notify the group coordinator about deleted topics.
+ val deletedTopicPartitions = new mutable.ArrayBuffer[TopicPartition]()
+ topicsDelta.deletedTopicIds().forEach { id =>
+ val topicImage = topicsDelta.image().getTopic(id)
+ topicImage.partitions().keySet().forEach {
+ id => deletedTopicPartitions += new TopicPartition(topicImage.name(), id)
+ }
+ }
+ if (!deletedTopicPartitions.isEmpty) {
+ groupCoordinator.handleDeletedPartitions(deletedTopicPartitions, RequestLocal.NoCaching)
+ }
+ }
+
+ // Apply configuration deltas.
+ Option(delta.configsDelta()).foreach { configsDelta =>
+ configsDelta.changes().keySet().forEach { configResource =>
+ val tag = configResource.`type`() match {
+ case ConfigResource.Type.TOPIC => Some(ConfigType.Topic)
+ case ConfigResource.Type.BROKER => Some(ConfigType.Broker)
+ case _ => None
+ }
+ tag.foreach { t =>
+ val newProperties = newImage.configs().configProperties(configResource)
+ dynamicConfigHandlers(t).processConfigChanges(configResource.name(), newProperties)
+ }
+ }
+ }
+
+ // Apply client quotas delta.
+ Option(delta.clientQuotasDelta()).foreach { clientQuotasDelta =>
+ clientQuotaMetadataManager.update(clientQuotasDelta)
+ }
+
+ if (_firstPublish) {
+ finishInitializingReplicaManager(newImage)
+ }
+ } catch {
+ case t: Throwable => error(s"Error publishing broker metadata at ${newHighestMetadataOffset}", t)
+ throw t
+ } finally {
+ _firstPublish = false
+ }
+ }
+
+ private def initializeManagers(): Unit = {
+ // Start log manager, which will perform (potentially lengthy)
+ // recovery-from-unclean-shutdown if required.
+ logManager.startup(metadataCache.getAllTopics())
+
+ // Start the replica manager.
+ replicaManager.startup()
Review comment:
A little surprising to find this here given `BrokerServer` owns the rest of the lifecycle for these managers. Not sure if it would be any better with a callback to `BrokerServer`?
##########
File path: core/src/main/scala/kafka/server/FinalizedFeatureCache.scala
##########
@@ -127,6 +131,22 @@ class FinalizedFeatureCache(private val brokerFeatures: BrokerFeatures) extends
}
}
+ def update(featuresDelta: FeaturesDelta, highestMetadataOffset: Long): Unit = {
+ val features = featuresAndEpoch.getOrElse(
+ FinalizedFeaturesAndEpoch(Features.emptyFinalizedFeatures(), -1))
+ val newFeatures = new util.HashMap[String, FinalizedVersionRange]()
+ newFeatures.putAll(features.features.features())
+ featuresDelta.changes().entrySet().forEach { e =>
+ e.getValue().asScala match {
+ case None => newFeatures.remove(e.getKey)
+ case Some(feature) => newFeatures.put(e.getKey,
+ new FinalizedVersionRange(feature.min(), feature.max()))
+ }
+ }
+ featuresAndEpoch = Some(FinalizedFeaturesAndEpoch(
+ Features.finalizedFeatures(newFeatures), highestMetadataOffset))
Review comment:
Wonder if it's worth wrapping `newFeatures` in an unmodifiable map.
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663275737
##########
File path: core/src/main/scala/kafka/server/ReplicaManager.scala
##########
@@ -2032,4 +2001,207 @@ class ReplicaManager(val config: KafkaConfig,
}
}
+ private[kafka] def getOrCreatePartition(tp: TopicPartition,
+ delta: TopicsDelta,
+ topicId: Uuid): Option[(Partition, Boolean)] = {
+ getPartition(tp) match {
+ case HostedPartition.Offline =>
+ stateChangeLogger.warn(s"Unable to bring up new local leader ${tp} " +
+ s"with topic id ${topicId} because it resides in an offline log " +
+ "directory.")
+ None
+
+ case HostedPartition.Online(partition) => Some(partition, false)
+
+ case HostedPartition.None =>
+ if (delta.image().topicsById().containsKey(topicId)) {
+ stateChangeLogger.error(s"Expected partition ${tp} with topic id " +
+ s"${topicId} to exist, but it was missing. Creating...")
+ } else {
+ stateChangeLogger.info(s"Creating new partition ${tp} with topic id " +
+ s"${topicId}.")
+ }
+ // it's a partition that we don't know about yet, so create it and mark it online
+ val partition = Partition(tp, time, this)
+ allPartitions.put(tp, HostedPartition.Online(partition))
+ Some(partition, true)
+ }
+ }
+
+ private[kafka] def calculateDeltaChanges(delta: TopicsDelta)
+ : (mutable.HashMap[TopicPartition, Boolean],
+ mutable.HashMap[TopicPartition, LocalLeaderInfo],
+ mutable.HashMap[TopicPartition, LocalLeaderInfo]) = {
+ val deleted = new mutable.HashMap[TopicPartition, Boolean]()
+ delta.deletedTopicIds().forEach { topicId =>
+ val topicImage = delta.image().getTopic(topicId)
+ topicImage.partitions().keySet().forEach { partitionId =>
+ deleted.put(new TopicPartition(topicImage.name(), partitionId), true)
+ }
+ }
+ val newLocalLeaders = new mutable.HashMap[TopicPartition, LocalLeaderInfo]()
+ val newLocalFollowers = new mutable.HashMap[TopicPartition, LocalLeaderInfo]()
+ delta.changedTopics().values().forEach { topicDelta =>
+ topicDelta.newLocalLeaders(config.nodeId).forEach { e =>
+ newLocalLeaders.put(new TopicPartition(topicDelta.name(), e.getKey),
+ LocalLeaderInfo(topicDelta.id(), e.getValue))
+ }
+ topicDelta.newLocalFollowers(config.nodeId).forEach { e =>
+ newLocalFollowers.put(new TopicPartition(topicDelta.name(), e.getKey),
+ LocalLeaderInfo(topicDelta.id(), e.getValue))
+ }
+ }
+ (deleted, newLocalLeaders, newLocalFollowers)
+ }
+
+ /**
+ * Apply a KRaft topic change delta.
+ *
+ * @param newImage The new metadata image.
+ * @param delta The delta to apply.
+ */
+ def applyDelta(newImage: MetadataImage, delta: TopicsDelta): Unit = {
+ // Before taking the lock, build some hash maps that we will need.
+ val (deleted, newLocalLeaders, newLocalFollowers) = calculateDeltaChanges(delta)
+
+ replicaStateChangeLock.synchronized {
+ // Handle deleted partitions. We need to do this first because we might subsequently
+ // create new partitions with the same names as the ones we are deleting here.
+ if (!deleted.isEmpty) {
+ stateChangeLogger.info(s"Deleting ${deleted.size} partition(s).")
+ stopPartitions(deleted).foreach { case (topicPartition, e) =>
+ if (e.isInstanceOf[KafkaStorageException]) {
+ stateChangeLogger.error(s"Unable to delete replica ${topicPartition} because " +
+ "the local replica for the partition is in an offline log directory")
+ } else {
+ stateChangeLogger.error(s"Unable to delete replica ${topicPartition} because " +
+ s"we got an unexpected ${e.getClass.getName} exception: ${e.getMessage}")
+ }
+ }
+ }
+ // Handle partitions which we are now the leader or follower for.
+ if (!newLocalLeaders.isEmpty || !newLocalFollowers.isEmpty) {
+ val lazyOffsetCheckpoints = new LazyOffsetCheckpoints(this.highWatermarkCheckpoints)
+ val changedPartitions = new mutable.HashSet[Partition]
+ if (!newLocalLeaders.isEmpty) {
+ applyLocalLeadersDelta(changedPartitions, delta, lazyOffsetCheckpoints, newLocalLeaders)
+ }
+ if (!newLocalFollowers.isEmpty) {
+ applyLocalFollowersDelta(changedPartitions, newImage, delta, lazyOffsetCheckpoints, newLocalFollowers)
+ }
+ maybeAddLogDirFetchers(changedPartitions, lazyOffsetCheckpoints,
+ name => Option(newImage.topics().getTopic(name)).map(_.id()))
+
+ def markPartitionOfflineIfNeeded(tp: TopicPartition): Unit = {
+ /*
+ * If there is offline log directory, a Partition object may have been created by getOrCreatePartition()
+ * before getOrCreateReplica() failed to create local replica due to KafkaStorageException.
+ * In this case ReplicaManager.allPartitions will map this topic-partition to an empty Partition object.
+ * we need to map this topic-partition to OfflinePartition instead.
+ */
+ if (localLog(tp).isEmpty)
+ markPartitionOffline(tp)
+ }
+ newLocalLeaders.keySet.foreach(markPartitionOfflineIfNeeded(_))
+ newLocalFollowers.keySet.foreach(markPartitionOfflineIfNeeded(_))
+
+ replicaFetcherManager.shutdownIdleFetcherThreads()
+ replicaAlterLogDirsManager.shutdownIdleFetcherThreads()
+ }
+ }
+ }
+
+ private def applyLocalLeadersDelta(changedPartitions: mutable.HashSet[Partition],
+ delta: TopicsDelta,
+ offsetCheckpoints: OffsetCheckpoints,
+ newLocalLeaders: mutable.HashMap[TopicPartition, LocalLeaderInfo]): Unit = {
+ stateChangeLogger.info(s"Transitioning ${newLocalLeaders.size} partition(s) to " +
+ "local leaders.")
+ replicaFetcherManager.removeFetcherForPartitions(newLocalLeaders.keySet)
+ newLocalLeaders.forKeyValue { case (tp, info) =>
+ getOrCreatePartition(tp, delta, info.topicId).foreach { case (partition, isNew) =>
+ try {
+ val state = info.partition.toLeaderAndIsrPartitionState(tp, isNew)
+ if (!partition.makeLeader(state, offsetCheckpoints, Some(info.topicId))) {
+ stateChangeLogger.info("Skipped the become-leader state change for " +
+ s"${tp} with topic id ${info.topicId} because this partition is " +
+ "already a local leader.")
+ }
+ changedPartitions.add(partition)
+ } catch {
+ case e: KafkaStorageException =>
+ stateChangeLogger.info(s"Skipped the become-leader state change for ${tp} " +
+ s"with topic id ${info.topicId} due to disk error ${e}")
+ val dirOpt = getLogDir(tp)
+ error(s"Error while making broker the leader for partition ${tp} in dir " +
+ s"${dirOpt}", e)
+ }
+ }
+ }
+ }
+
+ private def applyLocalFollowersDelta(changedPartitions: mutable.HashSet[Partition],
+ newImage: MetadataImage,
+ delta: TopicsDelta,
+ offsetCheckpoints: OffsetCheckpoints,
+ newLocalFollowers: mutable.HashMap[TopicPartition, LocalLeaderInfo]): Unit = {
+ stateChangeLogger.info(s"Transitioning ${newLocalFollowers.size} partition(s) to " +
+ "local followers.")
+ replicaFetcherManager.removeFetcherForPartitions(newLocalFollowers.keySet)
+ val shuttingDown = isShuttingDown.get()
+ val partitionsToMakeFollower = new mutable.HashMap[TopicPartition, InitialFetchState]
+ val newFollowerTopicSet = new mutable.HashSet[String]
+ newLocalFollowers.forKeyValue { case (tp, info) =>
+ getOrCreatePartition(tp, delta, info.topicId).foreach { case (partition, isNew) =>
+ try {
+ newFollowerTopicSet.add(tp.topic())
+
+ completeDelayedFetchOrProduceRequests(tp)
+
+ // Create the local replica even if the leader is unavailable. This is required
+ // to ensure that we include the partition's high watermark in the checkpoint
+ // file (see KAFKA-1647)
+ partition.createLogIfNotExists(isNew, false, offsetCheckpoints, Some(info.topicId))
+
+ if (shuttingDown) {
+ stateChangeLogger.trace(s"Unable to start fetching ${tp} with topic " +
+ s"ID ${info.topicId} because the replica manager is shutting down.")
+ } else {
+ val listenerName = config.interBrokerListenerName.value()
+ val leader = info.partition.leader
+ Option(newImage.cluster().broker(leader)).flatMap(_.node(listenerName).asScala) match {
+ case None => stateChangeLogger.trace(s"Unable to start fetching ${tp} " +
+ s"with topic ID ${info.topicId} from leader ${leader} because it is not " +
+ "alive.")
+ case Some(node) =>
+ val leaderEndPoint = new BrokerEndPoint(node.id(), node.host(), node.port())
+ val log = partition.localLogOrException
+ val fetchOffset = initialFetchOffset(log)
+ partitionsToMakeFollower.put(tp,
+ InitialFetchState(leaderEndPoint, partition.getLeaderEpoch, fetchOffset))
+ }
+ }
+ changedPartitions.add(partition)
+ } catch {
+ case e: Throwable => stateChangeLogger.error(s"Unable to start fetching ${tp} " +
Review comment:
Seems reasonable. The JavaDoc does say the partitions that had "unexpected errors" should end up there. I'll add 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] jacky1193610322 commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
jacky1193610322 commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r661895534
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
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] jacky1193610322 commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
jacky1193610322 commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r660054798
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
Thanks for your reply, it's right if will always keep the delta not replay before, which means we must persist the checkpoint offset every commit, but now we are not. for example, if the broker crash, we maybe replay the latest snapshot and the delta after the snapshot offset, but it may be the delta after the snapshot has been replay before. I don't sure it's right? thank you.
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
I'm sorry too, I have no problem if we always replay each record once and exactly once even if the broker crash.
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
I'm sorry too, I have no question if we always replay each record once and exactly once even if the broker crash.
--
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] hachikuji edited a comment on pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
hachikuji edited a comment on pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#issuecomment-873632735
@cmccabe The following test cases in `ClientQuotasRequestTest` fail consistently:
- `testDescribeClientQuotasMatchPartial`
- `testClientQuotasUnsupportedEntityTypes`
- `testDescribeClientQuotasMatchExact`
I checked on trunk and they are all passing.
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663270570
##########
File path: core/src/main/scala/kafka/server/BrokerServer.scala
##########
@@ -331,46 +327,40 @@ class BrokerServer(
new FetchSessionCache(config.maxIncrementalFetchSessionCacheSlots,
KafkaServer.MIN_INCREMENTAL_FETCH_SESSION_EVICTION_MS))
- // Start processing requests once we've caught up on the metadata log, recovered logs if necessary,
- // and started all services that we previously delayed starting.
- val raftSupport = RaftSupport(forwardingManager, metadataCache, quotaCache)
+ // Create the request processor objects.
+ val raftSupport = RaftSupport(forwardingManager, metadataCache)
dataPlaneRequestProcessor = new KafkaApis(socketServer.dataPlaneRequestChannel, raftSupport,
replicaManager, groupCoordinator, transactionCoordinator, autoTopicCreationManager,
- config.nodeId, config, configRepository, metadataCache, metrics, authorizer, quotaManagers,
+ config.nodeId, config, metadataCache, metadataCache, metrics, authorizer, quotaManagers,
fetchManager, brokerTopicStats, clusterId, time, tokenManager, apiVersionManager)
- dataPlaneRequestHandlerPool = new KafkaRequestHandlerPool(config.nodeId, socketServer.dataPlaneRequestChannel, dataPlaneRequestProcessor, time,
- config.numIoThreads, s"${SocketServer.DataPlaneMetricPrefix}RequestHandlerAvgIdlePercent", SocketServer.DataPlaneThreadPrefix)
-
- socketServer.controlPlaneRequestChannelOpt.foreach { controlPlaneRequestChannel =>
- controlPlaneRequestProcessor = new KafkaApis(controlPlaneRequestChannel, raftSupport,
- replicaManager, groupCoordinator, transactionCoordinator, autoTopicCreationManager,
- config.nodeId, config, configRepository, metadataCache, metrics, authorizer, quotaManagers,
- fetchManager, brokerTopicStats, clusterId, time, tokenManager, apiVersionManager)
+ dataPlaneRequestHandlerPool = new KafkaRequestHandlerPool(config.nodeId,
+ socketServer.dataPlaneRequestChannel, dataPlaneRequestProcessor, time,
+ config.numIoThreads, s"${SocketServer.DataPlaneMetricPrefix}RequestHandlerAvgIdlePercent",
+ SocketServer.DataPlaneThreadPrefix)
- controlPlaneRequestHandlerPool = new KafkaRequestHandlerPool(config.nodeId, socketServer.controlPlaneRequestChannelOpt.get, controlPlaneRequestProcessor, time,
- 1, s"${SocketServer.ControlPlaneMetricPrefix}RequestHandlerAvgIdlePercent", SocketServer.ControlPlaneThreadPrefix)
+ if (socketServer.controlPlaneRequestChannelOpt.isDefined) {
+ throw new RuntimeException("KIP-291 endpoints are not supported when in KRaft mode.")
Review comment:
I will add "control plane listeners" to the exception text.
Incidentally, this should be unreachable because of validation in `KafkaConfig.scala`, but it never hurts to 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.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [kafka] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663277869
##########
File path: core/src/main/scala/kafka/server/metadata/BrokerMetadataListener.scala
##########
@@ -70,230 +58,188 @@ class BrokerMetadataListener(
*/
@volatile private var _highestMetadataOffset = -1L
+ /**
+ * The current broker metadata image. Accessed only from the event queue thread.
+ */
+ private var _image = MetadataImage.EMPTY
+
+ /**
+ * The current metadata delta. Accessed only from the event queue thread.
+ */
+ private var _delta = new MetadataDelta(_image)
+
+ /**
+ * The object to use to publish new metadata changes, or None if this listener has not
+ * been activated yet.
+ */
+ private var _publisher: Option[MetadataPublisher] = None
+
+ /**
+ * The event queue which runs this listener.
+ */
val eventQueue = new KafkaEventQueue(time, logContext, threadNamePrefix.getOrElse(""))
+ /**
+ * Returns the highest metadata-offset. Thread-safe.
+ */
def highestMetadataOffset(): Long = _highestMetadataOffset
/**
* Handle new metadata records.
*/
- override def handleCommit(reader: BatchReader[ApiMessageAndVersion]): Unit = {
+ override def handleCommit(reader: BatchReader[ApiMessageAndVersion]): Unit =
eventQueue.append(new HandleCommitsEvent(reader))
+
+ class HandleCommitsEvent(reader: BatchReader[ApiMessageAndVersion])
+ extends EventQueue.FailureLoggingEvent(log) {
+ override def run(): Unit = {
+ val results = try {
+ val loadResults = loadBatches(_delta, reader)
+ if (isDebugEnabled) {
+ debug(s"Loaded new commits: ${loadResults}")
+ }
+ loadResults
+ } finally {
+ reader.close()
+ }
+ maybePublish(results.highestMetadataOffset)
+ }
}
/**
* Handle metadata snapshots
*/
- override def handleSnapshot(reader: SnapshotReader[ApiMessageAndVersion]): Unit = {
- // Loading snapshot on the broker is currently not supported.
- reader.close();
- throw new UnsupportedOperationException(s"Loading snapshot (${reader.snapshotId()}) is not supported")
- }
-
- // Visible for testing. It's useful to execute events synchronously in order
- // to make tests deterministic. This object is responsible for closing the reader.
- private[metadata] def execCommits(batchReader: BatchReader[ApiMessageAndVersion]): Unit = {
- new HandleCommitsEvent(batchReader).run()
- }
+ override def handleSnapshot(reader: SnapshotReader[ApiMessageAndVersion]): Unit =
+ eventQueue.append(new HandleSnapshotEvent(reader))
- class HandleCommitsEvent(
- reader: BatchReader[ApiMessageAndVersion]
- ) extends EventQueue.FailureLoggingEvent(log) {
+ class HandleSnapshotEvent(reader: SnapshotReader[ApiMessageAndVersion])
+ extends EventQueue.FailureLoggingEvent(log) {
override def run(): Unit = {
- try {
- while (reader.hasNext()) {
- apply(reader.next())
- }
+ val results = try {
+ info(s"Loading snapshot ${reader.snapshotId().offset}-${reader.snapshotId().epoch}.")
+ _delta = new MetadataDelta(_image) // Discard any previous deltas.
+ val loadResults = loadBatches(_delta, reader)
+ _delta.finishSnapshot()
Review comment:
Yeah, I thought about a few other names. Remove unreferenced? None of them seem great...
I added some more JavaDoc to `MetadataDelta#finishSnapshot`
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663430344
##########
File path: core/src/main/scala/kafka/server/BrokerServer.scala
##########
@@ -340,7 +338,8 @@ class BrokerServer(
SocketServer.DataPlaneThreadPrefix)
if (socketServer.controlPlaneRequestChannelOpt.isDefined) {
- throw new RuntimeException("KIP-291 endpoints are not supported when in KRaft mode.")
+ throw new RuntimeException("KIP-291 control plane listeners are not supported " +
Review comment:
ok
--
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] cmccabe merged pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe merged pull request #10931:
URL: https://github.com/apache/kafka/pull/10931
--
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] jacky1193610322 commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
jacky1193610322 commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r661501594
##########
File path: metadata/src/main/java/org/apache/kafka/image/TopicsDelta.java
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.metadata.PartitionChangeRecord;
+import org.apache.kafka.common.metadata.PartitionRecord;
+import org.apache.kafka.common.metadata.RemoveTopicRecord;
+import org.apache.kafka.common.metadata.TopicRecord;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+
+/**
+ * Represents changes to the topics in the metadata image.
+ */
+public final class TopicsDelta {
+ private final TopicsImage image;
+
+ /**
+ * A map from topic IDs to the topic deltas for each topic. Topics which have been
+ * deleted will not appear in this map.
+ */
+ private final Map<Uuid, TopicDelta> changedTopics = new HashMap<>();
+
+ /**
+ * The IDs of topics that exist in the image but that have been deleted. Note that if
+ * a topic does not exist in the image, it will also not exist in this set. Topics
+ * that are created and then deleted within the same delta will leave no trace.
+ */
+ private final Set<Uuid> deletedTopicIds = new HashSet<>();
Review comment:
Thank you. Can you point which class do that replays each record exactly once?
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663269838
##########
File path: core/src/main/scala/kafka/server/BrokerServer.scala
##########
@@ -264,19 +266,13 @@ class BrokerServer(
/* Add all reconfigurables for config change notification before starting the metadata listener */
config.dynamicConfig.addReconfigurables(this)
- val clientQuotaMetadataManager = new ClientQuotaMetadataManager(
- quotaManagers, socketServer.connectionQuotas, quotaCache)
+ // TODO : check that we're properly handling "ConfigType" Client, User, and Ip (which are not
Review comment:
It should work, but I need to do more testing. I'll take a look next week when I add more tests. The quotas stuff should be handled through the client quotas manager.
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663273638
##########
File path: core/src/main/scala/kafka/server/ReplicaManager.scala
##########
@@ -1302,7 +1278,8 @@ class ReplicaManager(val config: KafkaConfig,
stateChangeLogger.warn(stateControllerEpochErrorMessage)
throw new ControllerMovedException(stateChangeLogger.messageWithPrefix(stateControllerEpochErrorMessage))
} else {
- val deletedPartitions = metadataCache.updateMetadata(correlationId, updateMetadataRequest)
+ val zkMetadataCache = metadataCache.asInstanceOf[ZkMetadataCache]
Review comment:
That class brings in a bunch of stuff we don't need in `ReplicaManager`, though, like an `AdminZkClient` and `KafkaController`, etc...
--
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] cmccabe commented on pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#issuecomment-873740913
Should be fixed. The difference was in handling unknown entity types.
--
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] hachikuji commented on pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
hachikuji commented on pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#issuecomment-873632735
@cmccabe The following test cases in `ClientQuotasRequestTest` that fail consistently:
- `testDescribeClientQuotasMatchPartial`
- `testClientQuotasUnsupportedEntityTypes`
- `testDescribeClientQuotasMatchExact`
I checked on trunk and they are all passing.
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r661663935
##########
File path: metadata/src/main/java/org/apache/kafka/image/ClientQuotasImage.java
##########
@@ -0,0 +1,178 @@
+/*
+ * 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.image;
+
+import org.apache.kafka.common.message.DescribeClientQuotasRequestData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData.EntityData;
+import org.apache.kafka.common.message.DescribeClientQuotasResponseData.EntryData;
+import org.apache.kafka.common.quota.ClientQuotaEntity;
+import org.apache.kafka.server.common.ApiMessageAndVersion;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.common.protocol.Errors.INVALID_REQUEST;
+import static org.apache.kafka.common.protocol.Errors.UNSUPPORTED_VERSION;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_EXACT;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_DEFAULT;
+import static org.apache.kafka.common.requests.DescribeClientQuotasRequest.MATCH_TYPE_SPECIFIED;
+
+
+/**
+ * Represents the client quotas in the metadata image.
+ *
+ * This class is thread-safe.
+ */
+public final class ClientQuotasImage {
+ public final static ClientQuotasImage EMPTY = new ClientQuotasImage(Collections.emptyMap());
+
+ private final Map<ClientQuotaEntity, ClientQuotaImage> entities;
+
+ public ClientQuotasImage(Map<ClientQuotaEntity, ClientQuotaImage> entities) {
+ this.entities = entities;
+ }
+
+ public boolean isEmpty() {
+ return entities.isEmpty();
+ }
+
+ Map<ClientQuotaEntity, ClientQuotaImage> entities() {
+ return entities;
+ }
+
+ public void write(Consumer<List<ApiMessageAndVersion>> out) throws IOException {
+ for (Entry<ClientQuotaEntity, ClientQuotaImage> entry : entities.entrySet()) {
+ ClientQuotaEntity entity = entry.getKey();
+ ClientQuotaImage clientQuotaImage = entry.getValue();
+ clientQuotaImage.write(entity, out);
+ }
+ }
+
+ public DescribeClientQuotasResponseData describe(DescribeClientQuotasRequestData request) {
Review comment:
OK, I will add a check for those conditions.
--
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] cmccabe commented on a change in pull request #10931: KAFKA-12998: Implement broker-side KRaft snapshots (WIP)
Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #10931:
URL: https://github.com/apache/kafka/pull/10931#discussion_r663271546
##########
File path: core/src/main/scala/kafka/server/FinalizedFeatureCache.scala
##########
@@ -127,6 +131,22 @@ class FinalizedFeatureCache(private val brokerFeatures: BrokerFeatures) extends
}
}
+ def update(featuresDelta: FeaturesDelta, highestMetadataOffset: Long): Unit = {
+ val features = featuresAndEpoch.getOrElse(
+ FinalizedFeaturesAndEpoch(Features.emptyFinalizedFeatures(), -1))
+ val newFeatures = new util.HashMap[String, FinalizedVersionRange]()
+ newFeatures.putAll(features.features.features())
+ featuresDelta.changes().entrySet().forEach { e =>
+ e.getValue().asScala match {
+ case None => newFeatures.remove(e.getKey)
+ case Some(feature) => newFeatures.put(e.getKey,
+ new FinalizedVersionRange(feature.min(), feature.max()))
+ }
+ }
+ featuresAndEpoch = Some(FinalizedFeaturesAndEpoch(
+ Features.finalizedFeatures(newFeatures), highestMetadataOffset))
Review comment:
Yeah, let's do it. This shouldn't change often.
--
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