Search in sources :

Example 1 with TOPIC

use of org.apache.kafka.common.config.ConfigResource.Type.TOPIC in project kafka by apache.

the class QuorumControllerTest method testMissingInMemorySnapshot.

@Test
public void testMissingInMemorySnapshot() throws Exception {
    int numBrokers = 3;
    int numPartitions = 3;
    String topicName = "topic-name";
    try (LocalLogManagerTestEnv logEnv = new LocalLogManagerTestEnv(1, Optional.empty());
        QuorumControllerTestEnv controlEnv = new QuorumControllerTestEnv(logEnv, b -> b.setConfigDefs(CONFIGS))) {
        QuorumController controller = controlEnv.activeController();
        Map<Integer, Long> brokerEpochs = registerBrokers(controller, numBrokers);
        // Create a lot of partitions
        List<CreatableReplicaAssignment> partitions = IntStream.range(0, numPartitions).mapToObj(partitionIndex -> new CreatableReplicaAssignment().setPartitionIndex(partitionIndex).setBrokerIds(Arrays.asList(0, 1, 2))).collect(Collectors.toList());
        Uuid topicId = controller.createTopics(new CreateTopicsRequestData().setTopics(new CreatableTopicCollection(Collections.singleton(new CreatableTopic().setName(topicName).setNumPartitions(-1).setReplicationFactor((short) -1).setAssignments(new CreatableReplicaAssignmentCollection(partitions.iterator()))).iterator()))).get().topics().find(topicName).topicId();
        // Create a lot of alter isr
        List<AlterIsrRequestData.PartitionData> alterIsrs = IntStream.range(0, numPartitions).mapToObj(partitionIndex -> {
            PartitionRegistration partitionRegistration = controller.replicationControl().getPartition(topicId, partitionIndex);
            return new AlterIsrRequestData.PartitionData().setPartitionIndex(partitionIndex).setLeaderEpoch(partitionRegistration.leaderEpoch).setCurrentIsrVersion(partitionRegistration.partitionEpoch).setNewIsr(Arrays.asList(0, 1));
        }).collect(Collectors.toList());
        AlterIsrRequestData.TopicData topicData = new AlterIsrRequestData.TopicData().setName(topicName);
        topicData.partitions().addAll(alterIsrs);
        int leaderId = 0;
        AlterIsrRequestData alterIsrRequest = new AlterIsrRequestData().setBrokerId(leaderId).setBrokerEpoch(brokerEpochs.get(leaderId));
        alterIsrRequest.topics().add(topicData);
        logEnv.logManagers().get(0).resignAfterNonAtomicCommit();
        int oldClaimEpoch = controller.curClaimEpoch();
        assertThrows(ExecutionException.class, () -> controller.alterIsr(alterIsrRequest).get());
        // Wait for the controller to become active again
        assertSame(controller, controlEnv.activeController());
        assertTrue(oldClaimEpoch < controller.curClaimEpoch(), String.format("oldClaimEpoch = %s, newClaimEpoch = %s", oldClaimEpoch, controller.curClaimEpoch()));
        // Since the alterIsr partially failed we expect to see
        // some partitions to still have 2 in the ISR.
        int partitionsWithReplica2 = Utils.toList(controller.replicationControl().brokersToIsrs().partitionsWithBrokerInIsr(2)).size();
        int partitionsWithReplica0 = Utils.toList(controller.replicationControl().brokersToIsrs().partitionsWithBrokerInIsr(0)).size();
        assertEquals(numPartitions, partitionsWithReplica0);
        assertNotEquals(0, partitionsWithReplica2);
        assertTrue(partitionsWithReplica0 > partitionsWithReplica2, String.format("partitionsWithReplica0 = %s, partitionsWithReplica2 = %s", partitionsWithReplica0, partitionsWithReplica2));
    }
}
Also used : Arrays(java.util.Arrays) BrokerRegistrationRequestData(org.apache.kafka.common.message.BrokerRegistrationRequestData) BrokerIdNotRegisteredException(org.apache.kafka.common.errors.BrokerIdNotRegisteredException) ConfigurationControlManagerTest.entry(org.apache.kafka.controller.ConfigurationControlManagerTest.entry) Spliterators(java.util.Spliterators) Assertions.assertNotEquals(org.junit.jupiter.api.Assertions.assertNotEquals) ElectLeadersRequestData(org.apache.kafka.common.message.ElectLeadersRequestData) Listener(org.apache.kafka.common.message.BrokerRegistrationRequestData.Listener) CreatePartitionsTopicResult(org.apache.kafka.common.message.CreatePartitionsResponseData.CreatePartitionsTopicResult) Future(java.util.concurrent.Future) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) CreatePartitionsTopic(org.apache.kafka.common.message.CreatePartitionsRequestData.CreatePartitionsTopic) BufferSupplier(org.apache.kafka.common.utils.BufferSupplier) Map(java.util.Map) SET(org.apache.kafka.clients.admin.AlterConfigOp.OpType.SET) CreatableReplicaAssignmentCollection(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableReplicaAssignmentCollection) ListPartitionReassignmentsRequestData(org.apache.kafka.common.message.ListPartitionReassignmentsRequestData) TopicRecord(org.apache.kafka.common.metadata.TopicRecord) RawSnapshotReader(org.apache.kafka.snapshot.RawSnapshotReader) TestUtils(org.apache.kafka.test.TestUtils) PartitionRegistration(org.apache.kafka.metadata.PartitionRegistration) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) ConfigResourceExistenceChecker(org.apache.kafka.controller.QuorumController.ConfigResourceExistenceChecker) List(java.util.List) TopicIdPartition(org.apache.kafka.controller.BrokersToIsrs.TopicIdPartition) AllocateProducerIdsRequestData(org.apache.kafka.common.message.AllocateProducerIdsRequestData) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) BrokerEndpoint(org.apache.kafka.common.metadata.RegisterBrokerRecord.BrokerEndpoint) Optional(java.util.Optional) Errors(org.apache.kafka.common.protocol.Errors) UnknownTopicOrPartitionException(org.apache.kafka.common.errors.UnknownTopicOrPartitionException) CreateTopicsResponseData(org.apache.kafka.common.message.CreateTopicsResponseData) Spliterator(java.util.Spliterator) IntStream(java.util.stream.IntStream) Uuid(org.apache.kafka.common.Uuid) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) CONFIGS(org.apache.kafka.controller.ConfigurationControlManagerTest.CONFIGS) ListPartitionReassignmentsResponseData(org.apache.kafka.common.message.ListPartitionReassignmentsResponseData) LocalLogManagerTestEnv(org.apache.kafka.metalog.LocalLogManagerTestEnv) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) CreatableTopic(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic) ApiError(org.apache.kafka.common.requests.ApiError) TOPIC(org.apache.kafka.common.config.ConfigResource.Type.TOPIC) ConfigResource(org.apache.kafka.common.config.ConfigResource) BrokerHeartbeatReply(org.apache.kafka.metadata.BrokerHeartbeatReply) AlterPartitionReassignmentsRequestData(org.apache.kafka.common.message.AlterPartitionReassignmentsRequestData) ApiMessageAndVersion(org.apache.kafka.server.common.ApiMessageAndVersion) StreamSupport(java.util.stream.StreamSupport) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) SnapshotReader(org.apache.kafka.snapshot.SnapshotReader) Utils(org.apache.kafka.common.utils.Utils) RecordsSnapshotReader(org.apache.kafka.snapshot.RecordsSnapshotReader) MetadataRecordSerde(org.apache.kafka.metadata.MetadataRecordSerde) BROKER0(org.apache.kafka.controller.ConfigurationControlManagerTest.BROKER0) TimeoutException(org.apache.kafka.common.errors.TimeoutException) CreatableReplicaAssignment(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableReplicaAssignment) Iterator(java.util.Iterator) BrokerRegistrationReply(org.apache.kafka.metadata.BrokerRegistrationReply) ElectLeadersResponseData(org.apache.kafka.common.message.ElectLeadersResponseData) BrokerHeartbeatRequestData(org.apache.kafka.common.message.BrokerHeartbeatRequestData) BROKER(org.apache.kafka.common.config.ConfigResource.Type.BROKER) Batch(org.apache.kafka.raft.Batch) Assertions.assertSame(org.junit.jupiter.api.Assertions.assertSame) ExecutionException(java.util.concurrent.ExecutionException) AlterPartitionReassignmentsResponseData(org.apache.kafka.common.message.AlterPartitionReassignmentsResponseData) CreatableTopicCollection(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicCollection) CreateTopicsRequestData(org.apache.kafka.common.message.CreateTopicsRequestData) RecordTestUtils(org.apache.kafka.metadata.RecordTestUtils) ReassignableTopic(org.apache.kafka.common.message.AlterPartitionReassignmentsRequestData.ReassignableTopic) PartitionRecord(org.apache.kafka.common.metadata.PartitionRecord) AlterIsrRequestData(org.apache.kafka.common.message.AlterIsrRequestData) RegisterBrokerRecord(org.apache.kafka.common.metadata.RegisterBrokerRecord) HOURS(java.util.concurrent.TimeUnit.HOURS) Collections(java.util.Collections) Timeout(org.junit.jupiter.api.Timeout) ListenerCollection(org.apache.kafka.common.message.BrokerRegistrationRequestData.ListenerCollection) BrokerEndpointCollection(org.apache.kafka.common.metadata.RegisterBrokerRecord.BrokerEndpointCollection) ProducerIdsRecord(org.apache.kafka.common.metadata.ProducerIdsRecord) PartitionRegistration(org.apache.kafka.metadata.PartitionRegistration) LocalLogManagerTestEnv(org.apache.kafka.metalog.LocalLogManagerTestEnv) AlterIsrRequestData(org.apache.kafka.common.message.AlterIsrRequestData) BrokerEndpoint(org.apache.kafka.common.metadata.RegisterBrokerRecord.BrokerEndpoint) CreatableTopicCollection(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicCollection) Uuid(org.apache.kafka.common.Uuid) CreatableReplicaAssignment(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableReplicaAssignment) CreatableTopic(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic) CreateTopicsRequestData(org.apache.kafka.common.message.CreateTopicsRequestData) CreatableReplicaAssignmentCollection(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableReplicaAssignmentCollection) Test(org.junit.jupiter.api.Test)

Example 2 with TOPIC

use of org.apache.kafka.common.config.ConfigResource.Type.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 3 with TOPIC

use of org.apache.kafka.common.config.ConfigResource.Type.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)3 HashMap (java.util.HashMap)3 Iterator (java.util.Iterator)3 List (java.util.List)3 Map (java.util.Map)3 Optional (java.util.Optional)3 Collectors (java.util.stream.Collectors)3 SET (org.apache.kafka.clients.admin.AlterConfigOp.OpType.SET)3 Uuid (org.apache.kafka.common.Uuid)3 ConfigResource (org.apache.kafka.common.config.ConfigResource)3 TOPIC (org.apache.kafka.common.config.ConfigResource.Type.TOPIC)3 BrokerIdNotRegisteredException (org.apache.kafka.common.errors.BrokerIdNotRegisteredException)3 UnknownTopicOrPartitionException (org.apache.kafka.common.errors.UnknownTopicOrPartitionException)3 AlterIsrRequestData (org.apache.kafka.common.message.AlterIsrRequestData)3 AlterPartitionReassignmentsRequestData (org.apache.kafka.common.message.AlterPartitionReassignmentsRequestData)3 ReassignableTopic (org.apache.kafka.common.message.AlterPartitionReassignmentsRequestData.ReassignableTopic)3 SimpleImmutableEntry (java.util.AbstractMap.SimpleImmutableEntry)2 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 ListIterator (java.util.ListIterator)2