Search in sources :

Example 6 with Topic

use of org.apache.kafka.common.internals.Topic in project kafka by apache.

the class MetadataTest method testUpdateLastEpoch.

@Test
public void testUpdateLastEpoch() {
    TopicPartition tp = new TopicPartition("topic-1", 0);
    MetadataResponse metadataResponse = emptyMetadataResponse();
    metadata.updateWithCurrentRequestVersion(metadataResponse, false, 0L);
    // if we have no leader epoch, this call shouldn't do anything
    assertFalse(metadata.updateLastSeenEpochIfNewer(tp, 0));
    assertFalse(metadata.updateLastSeenEpochIfNewer(tp, 1));
    assertFalse(metadata.updateLastSeenEpochIfNewer(tp, 2));
    assertFalse(metadata.lastSeenLeaderEpoch(tp).isPresent());
    // Metadata with newer epoch is handled
    metadataResponse = RequestTestUtils.metadataUpdateWith("dummy", 1, Collections.emptyMap(), Collections.singletonMap("topic-1", 1), _tp -> 10);
    metadata.updateWithCurrentRequestVersion(metadataResponse, false, 1L);
    assertOptional(metadata.lastSeenLeaderEpoch(tp), leaderAndEpoch -> assertEquals(leaderAndEpoch.intValue(), 10));
    // Don't update to an older one
    assertFalse(metadata.updateLastSeenEpochIfNewer(tp, 1));
    assertOptional(metadata.lastSeenLeaderEpoch(tp), leaderAndEpoch -> assertEquals(leaderAndEpoch.intValue(), 10));
    // Don't cause update if it's the same one
    assertFalse(metadata.updateLastSeenEpochIfNewer(tp, 10));
    assertOptional(metadata.lastSeenLeaderEpoch(tp), leaderAndEpoch -> assertEquals(leaderAndEpoch.intValue(), 10));
    // Update if we see newer epoch
    assertTrue(metadata.updateLastSeenEpochIfNewer(tp, 12));
    assertOptional(metadata.lastSeenLeaderEpoch(tp), leaderAndEpoch -> assertEquals(leaderAndEpoch.intValue(), 12));
    metadataResponse = RequestTestUtils.metadataUpdateWith("dummy", 1, Collections.emptyMap(), Collections.singletonMap("topic-1", 1), _tp -> 12);
    metadata.updateWithCurrentRequestVersion(metadataResponse, false, 2L);
    assertOptional(metadata.lastSeenLeaderEpoch(tp), leaderAndEpoch -> assertEquals(leaderAndEpoch.intValue(), 12));
    // Don't overwrite metadata with older epoch
    metadataResponse = RequestTestUtils.metadataUpdateWith("dummy", 1, Collections.emptyMap(), Collections.singletonMap("topic-1", 1), _tp -> 11);
    metadata.updateWithCurrentRequestVersion(metadataResponse, false, 3L);
    assertOptional(metadata.lastSeenLeaderEpoch(tp), leaderAndEpoch -> assertEquals(leaderAndEpoch.intValue(), 12));
}
Also used : Uuid(org.apache.kafka.common.Uuid) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) MessageUtil(org.apache.kafka.common.protocol.MessageUtil) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) MockTime(org.apache.kafka.common.utils.MockTime) Arrays(java.util.Arrays) MockClusterResourceListener(org.apache.kafka.test.MockClusterResourceListener) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) RequestTestUtils(org.apache.kafka.common.requests.RequestTestUtils) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuffer(java.nio.ByteBuffer) HashSet(java.util.HashSet) Cluster(org.apache.kafka.common.Cluster) MetadataResponseBrokerCollection(org.apache.kafka.common.message.MetadataResponseData.MetadataResponseBrokerCollection) MetadataResponseTopic(org.apache.kafka.common.message.MetadataResponseData.MetadataResponseTopic) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) MetadataRequest(org.apache.kafka.common.requests.MetadataRequest) LogContext(org.apache.kafka.common.utils.LogContext) Map(java.util.Map) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) TestUtils.assertOptional(org.apache.kafka.test.TestUtils.assertOptional) Topic(org.apache.kafka.common.internals.Topic) Utils(org.apache.kafka.common.utils.Utils) TopicPartition(org.apache.kafka.common.TopicPartition) MetadataResponseTopicCollection(org.apache.kafka.common.message.MetadataResponseData.MetadataResponseTopicCollection) Time(org.apache.kafka.common.utils.Time) InvalidTopicException(org.apache.kafka.common.errors.InvalidTopicException) Set(java.util.Set) ClusterResourceListeners(org.apache.kafka.common.internals.ClusterResourceListeners) ApiKeys(org.apache.kafka.common.protocol.ApiKeys) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.jupiter.api.Test) Objects(java.util.Objects) List(java.util.List) MetadataResponsePartition(org.apache.kafka.common.message.MetadataResponseData.MetadataResponsePartition) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) TopicAuthorizationException(org.apache.kafka.common.errors.TopicAuthorizationException) Errors(org.apache.kafka.common.protocol.Errors) Optional(java.util.Optional) Node(org.apache.kafka.common.Node) MetadataResponseData(org.apache.kafka.common.message.MetadataResponseData) MetadataResponse(org.apache.kafka.common.requests.MetadataResponse) Collections(java.util.Collections) TopicPartition(org.apache.kafka.common.TopicPartition) MetadataResponse(org.apache.kafka.common.requests.MetadataResponse) Test(org.junit.jupiter.api.Test)

Example 7 with Topic

use of org.apache.kafka.common.internals.Topic in project kafka by apache.

the class MetadataTest method testMetadataMergeOnIdDowngrade.

@Test
public void testMetadataMergeOnIdDowngrade() {
    Time time = new MockTime();
    Map<String, Uuid> topicIds = new HashMap<>();
    final AtomicReference<Set<String>> retainTopics = new AtomicReference<>(new HashSet<>());
    metadata = new Metadata(refreshBackoffMs, metadataExpireMs, new LogContext(), new ClusterResourceListeners()) {

        @Override
        protected boolean retainTopic(String topic, boolean isInternal, long nowMs) {
            return retainTopics.get().contains(topic);
        }
    };
    // Initialize a metadata instance with two topics. Both will be retained.
    String clusterId = "clusterId";
    int nodes = 2;
    Map<String, Integer> topicPartitionCounts = new HashMap<>();
    topicPartitionCounts.put("validTopic1", 2);
    topicPartitionCounts.put("validTopic2", 3);
    retainTopics.set(Utils.mkSet("validTopic1", "validTopic2"));
    topicIds.put("validTopic1", Uuid.randomUuid());
    topicIds.put("validTopic2", Uuid.randomUuid());
    MetadataResponse metadataResponse = RequestTestUtils.metadataUpdateWithIds(clusterId, nodes, Collections.emptyMap(), topicPartitionCounts, _tp -> 100, topicIds);
    metadata.updateWithCurrentRequestVersion(metadataResponse, true, time.milliseconds());
    Map<String, Uuid> metadataTopicIds1 = metadata.topicIds();
    retainTopics.get().forEach(topic -> assertEquals(metadataTopicIds1.get(topic), topicIds.get(topic)));
    // Try removing the topic ID from keepValidTopic (simulating receiving a request from a controller with an older IBP)
    topicIds.remove("validTopic1");
    metadataResponse = RequestTestUtils.metadataUpdateWithIds(clusterId, nodes, Collections.emptyMap(), topicPartitionCounts, _tp -> 200, topicIds);
    metadata.updateWithCurrentRequestVersion(metadataResponse, true, time.milliseconds());
    Map<String, Uuid> metadataTopicIds2 = metadata.topicIds();
    retainTopics.get().forEach(topic -> assertEquals(metadataTopicIds2.get(topic), topicIds.get(topic)));
    Cluster cluster = metadata.fetch();
    // We still have the topic, but it just doesn't have an ID.
    assertEquals(Utils.mkSet("validTopic1", "validTopic2"), cluster.topics());
    assertEquals(2, cluster.partitionsForTopic("validTopic1").size());
    assertEquals(new HashSet<>(topicIds.values()), new HashSet<>(cluster.topicIds()));
    assertEquals(Uuid.ZERO_UUID, cluster.topicId("validTopic1"));
}
Also used : Uuid(org.apache.kafka.common.Uuid) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) MessageUtil(org.apache.kafka.common.protocol.MessageUtil) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) MockTime(org.apache.kafka.common.utils.MockTime) Arrays(java.util.Arrays) MockClusterResourceListener(org.apache.kafka.test.MockClusterResourceListener) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) RequestTestUtils(org.apache.kafka.common.requests.RequestTestUtils) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuffer(java.nio.ByteBuffer) HashSet(java.util.HashSet) Cluster(org.apache.kafka.common.Cluster) MetadataResponseBrokerCollection(org.apache.kafka.common.message.MetadataResponseData.MetadataResponseBrokerCollection) MetadataResponseTopic(org.apache.kafka.common.message.MetadataResponseData.MetadataResponseTopic) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) MetadataRequest(org.apache.kafka.common.requests.MetadataRequest) LogContext(org.apache.kafka.common.utils.LogContext) Map(java.util.Map) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) TestUtils.assertOptional(org.apache.kafka.test.TestUtils.assertOptional) Topic(org.apache.kafka.common.internals.Topic) Utils(org.apache.kafka.common.utils.Utils) TopicPartition(org.apache.kafka.common.TopicPartition) MetadataResponseTopicCollection(org.apache.kafka.common.message.MetadataResponseData.MetadataResponseTopicCollection) Time(org.apache.kafka.common.utils.Time) InvalidTopicException(org.apache.kafka.common.errors.InvalidTopicException) Set(java.util.Set) ClusterResourceListeners(org.apache.kafka.common.internals.ClusterResourceListeners) ApiKeys(org.apache.kafka.common.protocol.ApiKeys) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.jupiter.api.Test) Objects(java.util.Objects) List(java.util.List) MetadataResponsePartition(org.apache.kafka.common.message.MetadataResponseData.MetadataResponsePartition) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) TopicAuthorizationException(org.apache.kafka.common.errors.TopicAuthorizationException) Errors(org.apache.kafka.common.protocol.Errors) Optional(java.util.Optional) Node(org.apache.kafka.common.Node) MetadataResponseData(org.apache.kafka.common.message.MetadataResponseData) MetadataResponse(org.apache.kafka.common.requests.MetadataResponse) Collections(java.util.Collections) ClusterResourceListeners(org.apache.kafka.common.internals.ClusterResourceListeners) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) LogContext(org.apache.kafka.common.utils.LogContext) Cluster(org.apache.kafka.common.Cluster) MockTime(org.apache.kafka.common.utils.MockTime) Time(org.apache.kafka.common.utils.Time) AtomicReference(java.util.concurrent.atomic.AtomicReference) Uuid(org.apache.kafka.common.Uuid) MetadataResponse(org.apache.kafka.common.requests.MetadataResponse) MockTime(org.apache.kafka.common.utils.MockTime) Test(org.junit.jupiter.api.Test)

Example 8 with Topic

use of org.apache.kafka.common.internals.Topic in project kafka by apache.

the class ReplicationControlManager method createTopics.

ControllerResult<CreateTopicsResponseData> createTopics(CreateTopicsRequestData request) {
    Map<String, ApiError> topicErrors = new HashMap<>();
    List<ApiMessageAndVersion> records = new ArrayList<>();
    // Check the topic names.
    validateNewTopicNames(topicErrors, request.topics());
    // Identify topics that already exist and mark them with the appropriate error
    request.topics().stream().filter(creatableTopic -> topicsByName.containsKey(creatableTopic.name())).forEach(t -> topicErrors.put(t.name(), new ApiError(Errors.TOPIC_ALREADY_EXISTS, "Topic '" + t.name() + "' already exists.")));
    // Verify that the configurations for the new topics are OK, and figure out what
    // ConfigRecords should be created.
    Map<ConfigResource, Map<String, Entry<OpType, String>>> configChanges = computeConfigChanges(topicErrors, request.topics());
    ControllerResult<Map<ConfigResource, ApiError>> configResult = configurationControl.incrementalAlterConfigs(configChanges, NO_OP_EXISTENCE_CHECKER);
    for (Entry<ConfigResource, ApiError> entry : configResult.response().entrySet()) {
        if (entry.getValue().isFailure()) {
            topicErrors.put(entry.getKey().name(), entry.getValue());
        }
    }
    records.addAll(configResult.records());
    // Try to create whatever topics are needed.
    Map<String, CreatableTopicResult> successes = new HashMap<>();
    for (CreatableTopic topic : request.topics()) {
        if (topicErrors.containsKey(topic.name()))
            continue;
        ApiError error;
        try {
            error = createTopic(topic, records, successes);
        } catch (ApiException e) {
            error = ApiError.fromThrowable(e);
        }
        if (error.isFailure()) {
            topicErrors.put(topic.name(), error);
        }
    }
    // Create responses for all topics.
    CreateTopicsResponseData data = new CreateTopicsResponseData();
    StringBuilder resultsBuilder = new StringBuilder();
    String resultsPrefix = "";
    for (CreatableTopic topic : request.topics()) {
        ApiError error = topicErrors.get(topic.name());
        if (error != null) {
            data.topics().add(new CreatableTopicResult().setName(topic.name()).setErrorCode(error.error().code()).setErrorMessage(error.message()));
            resultsBuilder.append(resultsPrefix).append(topic).append(": ").append(error.error()).append(" (").append(error.message()).append(")");
            resultsPrefix = ", ";
            continue;
        }
        CreatableTopicResult result = successes.get(topic.name());
        data.topics().add(result);
        resultsBuilder.append(resultsPrefix).append(topic).append(": ").append("SUCCESS");
        resultsPrefix = ", ";
    }
    if (request.validateOnly()) {
        log.info("Validate-only CreateTopics result(s): {}", resultsBuilder.toString());
        return ControllerResult.atomicOf(Collections.emptyList(), data);
    } else {
        log.info("CreateTopics result(s): {}", resultsBuilder.toString());
        return ControllerResult.atomicOf(records, data);
    }
}
Also used : ListPartitionReassignmentsTopics(org.apache.kafka.common.message.ListPartitionReassignmentsRequestData.ListPartitionReassignmentsTopics) OpType(org.apache.kafka.clients.admin.AlterConfigOp.OpType) InvalidReplicationFactorException(org.apache.kafka.common.errors.InvalidReplicationFactorException) ElectLeadersRequestData(org.apache.kafka.common.message.ElectLeadersRequestData) CreatePartitionsTopic(org.apache.kafka.common.message.CreatePartitionsRequestData.CreatePartitionsTopic) PartitionResult(org.apache.kafka.common.message.ElectLeadersResponseData.PartitionResult) LogContext(org.apache.kafka.common.utils.LogContext) Map(java.util.Map) TimelineInteger(org.apache.kafka.timeline.TimelineInteger) SET(org.apache.kafka.clients.admin.AlterConfigOp.OpType.SET) AlterIsrResponseData(org.apache.kafka.common.message.AlterIsrResponseData) NoReassignmentInProgressException(org.apache.kafka.common.errors.NoReassignmentInProgressException) INVALID_REQUEST(org.apache.kafka.common.protocol.Errors.INVALID_REQUEST) InvalidTopicException(org.apache.kafka.common.errors.InvalidTopicException) UNREGISTER_BROKER_RECORD(org.apache.kafka.common.metadata.MetadataRecordType.UNREGISTER_BROKER_RECORD) SnapshotRegistry(org.apache.kafka.timeline.SnapshotRegistry) NO_LEADER(org.apache.kafka.metadata.LeaderConstants.NO_LEADER) InvalidPartitionsException(org.apache.kafka.common.errors.InvalidPartitionsException) UNKNOWN_TOPIC_ID(org.apache.kafka.common.protocol.Errors.UNKNOWN_TOPIC_ID) PartitionChangeRecord(org.apache.kafka.common.metadata.PartitionChangeRecord) Errors(org.apache.kafka.common.protocol.Errors) UnknownTopicOrPartitionException(org.apache.kafka.common.errors.UnknownTopicOrPartitionException) CreatableTopicResult(org.apache.kafka.common.message.CreateTopicsResponseData.CreatableTopicResult) RemoveTopicRecord(org.apache.kafka.common.metadata.RemoveTopicRecord) TimelineHashMap(org.apache.kafka.timeline.TimelineHashMap) NO_REASSIGNMENT_IN_PROGRESS(org.apache.kafka.common.protocol.Errors.NO_REASSIGNMENT_IN_PROGRESS) BrokerRegistration(org.apache.kafka.metadata.BrokerRegistration) Supplier(java.util.function.Supplier) TOPIC(org.apache.kafka.common.config.ConfigResource.Type.TOPIC) ArrayList(java.util.ArrayList) FENCED_LEADER_EPOCH(org.apache.kafka.common.protocol.Errors.FENCED_LEADER_EPOCH) UnfenceBrokerRecord(org.apache.kafka.common.metadata.UnfenceBrokerRecord) ElectionType(org.apache.kafka.common.ElectionType) BrokerHeartbeatReply(org.apache.kafka.metadata.BrokerHeartbeatReply) AlterPartitionReassignmentsRequestData(org.apache.kafka.common.message.AlterPartitionReassignmentsRequestData) UnknownTopicIdException(org.apache.kafka.common.errors.UnknownTopicIdException) Topic(org.apache.kafka.common.internals.Topic) CreatableReplicaAssignment(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableReplicaAssignment) FENCE_BROKER_RECORD(org.apache.kafka.common.metadata.MetadataRecordType.FENCE_BROKER_RECORD) ElectLeadersResponseData(org.apache.kafka.common.message.ElectLeadersResponseData) ReassignablePartition(org.apache.kafka.common.message.AlterPartitionReassignmentsRequestData.ReassignablePartition) BrokerHeartbeatRequestData(org.apache.kafka.common.message.BrokerHeartbeatRequestData) CreatableTopicCollection(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicCollection) CreateTopicsRequestData(org.apache.kafka.common.message.CreateTopicsRequestData) ReassignableTopic(org.apache.kafka.common.message.AlterPartitionReassignmentsRequestData.ReassignableTopic) PartitionRecord(org.apache.kafka.common.metadata.PartitionRecord) CreatePartitionsAssignment(org.apache.kafka.common.message.CreatePartitionsRequestData.CreatePartitionsAssignment) UNFENCE_BROKER_RECORD(org.apache.kafka.common.metadata.MetadataRecordType.UNFENCE_BROKER_RECORD) PARTITION_RECORD(org.apache.kafka.common.metadata.MetadataRecordType.PARTITION_RECORD) BrokerIdNotRegisteredException(org.apache.kafka.common.errors.BrokerIdNotRegisteredException) ListIterator(java.util.ListIterator) CreatePartitionsTopicResult(org.apache.kafka.common.message.CreatePartitionsResponseData.CreatePartitionsTopicResult) ReassignableTopicResponse(org.apache.kafka.common.message.AlterPartitionReassignmentsResponseData.ReassignableTopicResponse) ReplicaElectionResult(org.apache.kafka.common.message.ElectLeadersResponseData.ReplicaElectionResult) TOPIC_RECORD(org.apache.kafka.common.metadata.MetadataRecordType.TOPIC_RECORD) FenceBrokerRecord(org.apache.kafka.common.metadata.FenceBrokerRecord) TopicRecord(org.apache.kafka.common.metadata.TopicRecord) Collection(java.util.Collection) UnregisterBrokerRecord(org.apache.kafka.common.metadata.UnregisterBrokerRecord) TopicPartitions(org.apache.kafka.common.message.ElectLeadersRequestData.TopicPartitions) PartitionRegistration(org.apache.kafka.metadata.PartitionRegistration) Collectors(java.util.stream.Collectors) Replicas(org.apache.kafka.metadata.Replicas) INVALID_UPDATE_VERSION(org.apache.kafka.common.protocol.Errors.INVALID_UPDATE_VERSION) TopicIdPartition(org.apache.kafka.controller.BrokersToIsrs.TopicIdPartition) List(java.util.List) NO_LEADER_CHANGE(org.apache.kafka.metadata.LeaderConstants.NO_LEADER_CHANGE) Entry(java.util.Map.Entry) Optional(java.util.Optional) CreateTopicsResponseData(org.apache.kafka.common.message.CreateTopicsResponseData) Uuid(org.apache.kafka.common.Uuid) ReassignablePartitionResponse(org.apache.kafka.common.message.AlterPartitionReassignmentsResponseData.ReassignablePartitionResponse) ListPartitionReassignmentsResponseData(org.apache.kafka.common.message.ListPartitionReassignmentsResponseData) HashMap(java.util.HashMap) REMOVE_TOPIC_RECORD(org.apache.kafka.common.metadata.MetadataRecordType.REMOVE_TOPIC_RECORD) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) CreatableTopic(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic) Function(java.util.function.Function) OptionalInt(java.util.OptionalInt) ApiError(org.apache.kafka.common.requests.ApiError) UnknownServerException(org.apache.kafka.common.errors.UnknownServerException) ConfigResource(org.apache.kafka.common.config.ConfigResource) ApiMessageAndVersion(org.apache.kafka.server.common.ApiMessageAndVersion) PolicyViolationException(org.apache.kafka.common.errors.PolicyViolationException) OngoingPartitionReassignment(org.apache.kafka.common.message.ListPartitionReassignmentsResponseData.OngoingPartitionReassignment) OngoingTopicReassignment(org.apache.kafka.common.message.ListPartitionReassignmentsResponseData.OngoingTopicReassignment) NoSuchElementException(java.util.NoSuchElementException) UNKNOWN_TOPIC_OR_PARTITION(org.apache.kafka.common.protocol.Errors.UNKNOWN_TOPIC_OR_PARTITION) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) InvalidReplicaAssignmentException(org.apache.kafka.common.errors.InvalidReplicaAssignmentException) NO_OP_EXISTENCE_CHECKER(org.apache.kafka.controller.ConfigurationControlManager.NO_OP_EXISTENCE_CHECKER) AlterPartitionReassignmentsResponseData(org.apache.kafka.common.message.AlterPartitionReassignmentsResponseData) CreateTopicPolicy(org.apache.kafka.server.policy.CreateTopicPolicy) AlterIsrRequestData(org.apache.kafka.common.message.AlterIsrRequestData) InvalidRequestException(org.apache.kafka.common.errors.InvalidRequestException) Collections(java.util.Collections) ApiException(org.apache.kafka.common.errors.ApiException) TimelineHashMap(org.apache.kafka.timeline.TimelineHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CreateTopicsResponseData(org.apache.kafka.common.message.CreateTopicsResponseData) ConfigResource(org.apache.kafka.common.config.ConfigResource) CreatableTopic(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic) ApiMessageAndVersion(org.apache.kafka.server.common.ApiMessageAndVersion) CreatableTopicResult(org.apache.kafka.common.message.CreateTopicsResponseData.CreatableTopicResult) OpType(org.apache.kafka.clients.admin.AlterConfigOp.OpType) ApiError(org.apache.kafka.common.requests.ApiError) Map(java.util.Map) TimelineHashMap(org.apache.kafka.timeline.TimelineHashMap) HashMap(java.util.HashMap) ApiException(org.apache.kafka.common.errors.ApiException)

Example 9 with Topic

use of org.apache.kafka.common.internals.Topic in project kafka by apache.

the class ReplicationControlManager method generateLeaderAndIsrUpdates.

/**
 * Iterate over a sequence of partitions and generate ISR changes and/or leader
 * changes if necessary.
 *
 * @param context           A human-readable context string used in log4j logging.
 * @param brokerToRemove    NO_LEADER if no broker is being removed; the ID of the
 *                          broker to remove from the ISR and leadership, otherwise.
 * @param brokerToAdd       NO_LEADER if no broker is being added; the ID of the
 *                          broker which is now eligible to be a leader, otherwise.
 * @param records           A list of records which we will append to.
 * @param iterator          The iterator containing the partitions to examine.
 */
void generateLeaderAndIsrUpdates(String context, int brokerToRemove, int brokerToAdd, List<ApiMessageAndVersion> records, Iterator<TopicIdPartition> iterator) {
    int oldSize = records.size();
    // If the caller passed a valid broker ID for brokerToAdd, rather than passing
    // NO_LEADER, that node will be considered an acceptable leader even if it is
    // currently fenced. This is useful when handling unfencing. The reason is that
    // while we're generating the records to handle unfencing, the ClusterControlManager
    // still shows the node as fenced.
    // 
    // Similarly, if the caller passed a valid broker ID for brokerToRemove, rather
    // than passing NO_LEADER, that node will never be considered an acceptable leader.
    // This is useful when handling a newly fenced node. We also exclude brokerToRemove
    // from the target ISR, but we need to exclude it here too, to handle the case
    // where there is an unclean leader election which chooses a leader from outside
    // the ISR.
    Function<Integer, Boolean> isAcceptableLeader = r -> (r != brokerToRemove) && (r == brokerToAdd || clusterControl.unfenced(r));
    while (iterator.hasNext()) {
        TopicIdPartition topicIdPart = iterator.next();
        TopicControlInfo topic = topics.get(topicIdPart.topicId());
        if (topic == null) {
            throw new RuntimeException("Topic ID " + topicIdPart.topicId() + " existed in isrMembers, but not in the topics map.");
        }
        PartitionRegistration partition = topic.parts.get(topicIdPart.partitionId());
        if (partition == null) {
            throw new RuntimeException("Partition " + topicIdPart + " existed in isrMembers, but not in the partitions map.");
        }
        PartitionChangeBuilder builder = new PartitionChangeBuilder(partition, topicIdPart.topicId(), topicIdPart.partitionId(), isAcceptableLeader, () -> configurationControl.uncleanLeaderElectionEnabledForTopic(topic.name));
        // Note: if brokerToRemove was passed as NO_LEADER, this is a no-op (the new
        // target ISR will be the same as the old one).
        builder.setTargetIsr(Replicas.toList(Replicas.copyWithout(partition.isr, brokerToRemove)));
        builder.build().ifPresent(records::add);
    }
    if (records.size() != oldSize) {
        if (log.isDebugEnabled()) {
            StringBuilder bld = new StringBuilder();
            String prefix = "";
            for (ListIterator<ApiMessageAndVersion> iter = records.listIterator(oldSize); iter.hasNext(); ) {
                ApiMessageAndVersion apiMessageAndVersion = iter.next();
                PartitionChangeRecord record = (PartitionChangeRecord) apiMessageAndVersion.message();
                bld.append(prefix).append(topics.get(record.topicId()).name).append("-").append(record.partitionId());
                prefix = ", ";
            }
            log.debug("{}: changing partition(s): {}", context, bld.toString());
        } else if (log.isInfoEnabled()) {
            log.info("{}: changing {} partition(s)", context, records.size() - oldSize);
        }
    }
}
Also used : ListPartitionReassignmentsTopics(org.apache.kafka.common.message.ListPartitionReassignmentsRequestData.ListPartitionReassignmentsTopics) OpType(org.apache.kafka.clients.admin.AlterConfigOp.OpType) InvalidReplicationFactorException(org.apache.kafka.common.errors.InvalidReplicationFactorException) ElectLeadersRequestData(org.apache.kafka.common.message.ElectLeadersRequestData) CreatePartitionsTopic(org.apache.kafka.common.message.CreatePartitionsRequestData.CreatePartitionsTopic) PartitionResult(org.apache.kafka.common.message.ElectLeadersResponseData.PartitionResult) LogContext(org.apache.kafka.common.utils.LogContext) Map(java.util.Map) TimelineInteger(org.apache.kafka.timeline.TimelineInteger) SET(org.apache.kafka.clients.admin.AlterConfigOp.OpType.SET) AlterIsrResponseData(org.apache.kafka.common.message.AlterIsrResponseData) NoReassignmentInProgressException(org.apache.kafka.common.errors.NoReassignmentInProgressException) INVALID_REQUEST(org.apache.kafka.common.protocol.Errors.INVALID_REQUEST) InvalidTopicException(org.apache.kafka.common.errors.InvalidTopicException) UNREGISTER_BROKER_RECORD(org.apache.kafka.common.metadata.MetadataRecordType.UNREGISTER_BROKER_RECORD) SnapshotRegistry(org.apache.kafka.timeline.SnapshotRegistry) NO_LEADER(org.apache.kafka.metadata.LeaderConstants.NO_LEADER) InvalidPartitionsException(org.apache.kafka.common.errors.InvalidPartitionsException) UNKNOWN_TOPIC_ID(org.apache.kafka.common.protocol.Errors.UNKNOWN_TOPIC_ID) PartitionChangeRecord(org.apache.kafka.common.metadata.PartitionChangeRecord) Errors(org.apache.kafka.common.protocol.Errors) UnknownTopicOrPartitionException(org.apache.kafka.common.errors.UnknownTopicOrPartitionException) CreatableTopicResult(org.apache.kafka.common.message.CreateTopicsResponseData.CreatableTopicResult) RemoveTopicRecord(org.apache.kafka.common.metadata.RemoveTopicRecord) TimelineHashMap(org.apache.kafka.timeline.TimelineHashMap) NO_REASSIGNMENT_IN_PROGRESS(org.apache.kafka.common.protocol.Errors.NO_REASSIGNMENT_IN_PROGRESS) BrokerRegistration(org.apache.kafka.metadata.BrokerRegistration) Supplier(java.util.function.Supplier) TOPIC(org.apache.kafka.common.config.ConfigResource.Type.TOPIC) ArrayList(java.util.ArrayList) FENCED_LEADER_EPOCH(org.apache.kafka.common.protocol.Errors.FENCED_LEADER_EPOCH) UnfenceBrokerRecord(org.apache.kafka.common.metadata.UnfenceBrokerRecord) ElectionType(org.apache.kafka.common.ElectionType) BrokerHeartbeatReply(org.apache.kafka.metadata.BrokerHeartbeatReply) AlterPartitionReassignmentsRequestData(org.apache.kafka.common.message.AlterPartitionReassignmentsRequestData) UnknownTopicIdException(org.apache.kafka.common.errors.UnknownTopicIdException) Topic(org.apache.kafka.common.internals.Topic) CreatableReplicaAssignment(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableReplicaAssignment) FENCE_BROKER_RECORD(org.apache.kafka.common.metadata.MetadataRecordType.FENCE_BROKER_RECORD) ElectLeadersResponseData(org.apache.kafka.common.message.ElectLeadersResponseData) ReassignablePartition(org.apache.kafka.common.message.AlterPartitionReassignmentsRequestData.ReassignablePartition) BrokerHeartbeatRequestData(org.apache.kafka.common.message.BrokerHeartbeatRequestData) CreatableTopicCollection(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicCollection) CreateTopicsRequestData(org.apache.kafka.common.message.CreateTopicsRequestData) ReassignableTopic(org.apache.kafka.common.message.AlterPartitionReassignmentsRequestData.ReassignableTopic) PartitionRecord(org.apache.kafka.common.metadata.PartitionRecord) CreatePartitionsAssignment(org.apache.kafka.common.message.CreatePartitionsRequestData.CreatePartitionsAssignment) UNFENCE_BROKER_RECORD(org.apache.kafka.common.metadata.MetadataRecordType.UNFENCE_BROKER_RECORD) PARTITION_RECORD(org.apache.kafka.common.metadata.MetadataRecordType.PARTITION_RECORD) BrokerIdNotRegisteredException(org.apache.kafka.common.errors.BrokerIdNotRegisteredException) ListIterator(java.util.ListIterator) CreatePartitionsTopicResult(org.apache.kafka.common.message.CreatePartitionsResponseData.CreatePartitionsTopicResult) ReassignableTopicResponse(org.apache.kafka.common.message.AlterPartitionReassignmentsResponseData.ReassignableTopicResponse) ReplicaElectionResult(org.apache.kafka.common.message.ElectLeadersResponseData.ReplicaElectionResult) TOPIC_RECORD(org.apache.kafka.common.metadata.MetadataRecordType.TOPIC_RECORD) FenceBrokerRecord(org.apache.kafka.common.metadata.FenceBrokerRecord) TopicRecord(org.apache.kafka.common.metadata.TopicRecord) Collection(java.util.Collection) UnregisterBrokerRecord(org.apache.kafka.common.metadata.UnregisterBrokerRecord) TopicPartitions(org.apache.kafka.common.message.ElectLeadersRequestData.TopicPartitions) PartitionRegistration(org.apache.kafka.metadata.PartitionRegistration) Collectors(java.util.stream.Collectors) Replicas(org.apache.kafka.metadata.Replicas) INVALID_UPDATE_VERSION(org.apache.kafka.common.protocol.Errors.INVALID_UPDATE_VERSION) TopicIdPartition(org.apache.kafka.controller.BrokersToIsrs.TopicIdPartition) List(java.util.List) NO_LEADER_CHANGE(org.apache.kafka.metadata.LeaderConstants.NO_LEADER_CHANGE) Entry(java.util.Map.Entry) Optional(java.util.Optional) CreateTopicsResponseData(org.apache.kafka.common.message.CreateTopicsResponseData) Uuid(org.apache.kafka.common.Uuid) ReassignablePartitionResponse(org.apache.kafka.common.message.AlterPartitionReassignmentsResponseData.ReassignablePartitionResponse) ListPartitionReassignmentsResponseData(org.apache.kafka.common.message.ListPartitionReassignmentsResponseData) HashMap(java.util.HashMap) REMOVE_TOPIC_RECORD(org.apache.kafka.common.metadata.MetadataRecordType.REMOVE_TOPIC_RECORD) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) CreatableTopic(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic) Function(java.util.function.Function) OptionalInt(java.util.OptionalInt) ApiError(org.apache.kafka.common.requests.ApiError) UnknownServerException(org.apache.kafka.common.errors.UnknownServerException) ConfigResource(org.apache.kafka.common.config.ConfigResource) ApiMessageAndVersion(org.apache.kafka.server.common.ApiMessageAndVersion) PolicyViolationException(org.apache.kafka.common.errors.PolicyViolationException) OngoingPartitionReassignment(org.apache.kafka.common.message.ListPartitionReassignmentsResponseData.OngoingPartitionReassignment) OngoingTopicReassignment(org.apache.kafka.common.message.ListPartitionReassignmentsResponseData.OngoingTopicReassignment) NoSuchElementException(java.util.NoSuchElementException) UNKNOWN_TOPIC_OR_PARTITION(org.apache.kafka.common.protocol.Errors.UNKNOWN_TOPIC_OR_PARTITION) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) InvalidReplicaAssignmentException(org.apache.kafka.common.errors.InvalidReplicaAssignmentException) NO_OP_EXISTENCE_CHECKER(org.apache.kafka.controller.ConfigurationControlManager.NO_OP_EXISTENCE_CHECKER) AlterPartitionReassignmentsResponseData(org.apache.kafka.common.message.AlterPartitionReassignmentsResponseData) CreateTopicPolicy(org.apache.kafka.server.policy.CreateTopicPolicy) AlterIsrRequestData(org.apache.kafka.common.message.AlterIsrRequestData) InvalidRequestException(org.apache.kafka.common.errors.InvalidRequestException) Collections(java.util.Collections) ApiException(org.apache.kafka.common.errors.ApiException) PartitionRegistration(org.apache.kafka.metadata.PartitionRegistration) PartitionChangeRecord(org.apache.kafka.common.metadata.PartitionChangeRecord) TopicIdPartition(org.apache.kafka.controller.BrokersToIsrs.TopicIdPartition) TimelineInteger(org.apache.kafka.timeline.TimelineInteger) ApiMessageAndVersion(org.apache.kafka.server.common.ApiMessageAndVersion)

Aggregations

Collections (java.util.Collections)9 HashMap (java.util.HashMap)9 List (java.util.List)9 Map (java.util.Map)9 Optional (java.util.Optional)9 Uuid (org.apache.kafka.common.Uuid)9 InvalidTopicException (org.apache.kafka.common.errors.InvalidTopicException)9 Topic (org.apache.kafka.common.internals.Topic)9 Errors (org.apache.kafka.common.protocol.Errors)9 LogContext (org.apache.kafka.common.utils.LogContext)9 InetSocketAddress (java.net.InetSocketAddress)7 ByteBuffer (java.nio.ByteBuffer)7 Arrays (java.util.Arrays)7 HashSet (java.util.HashSet)7 Objects (java.util.Objects)7 Set (java.util.Set)7 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 Cluster (org.apache.kafka.common.Cluster)7 Node (org.apache.kafka.common.Node)7 TopicPartition (org.apache.kafka.common.TopicPartition)7