Search in sources :

Example 81 with Errors

use of org.apache.kafka.common.protocol.Errors in project kafka by apache.

the class ReplicationControlManagerTest method buildElectLeadersResponse.

private ElectLeadersResponseData buildElectLeadersResponse(Errors topLevelError, boolean electAllPartitions, Map<TopicPartition, ApiError> errors) {
    Map<String, List<Map.Entry<TopicPartition, ApiError>>> errorsByTopic = errors.entrySet().stream().collect(Collectors.groupingBy(entry -> entry.getKey().topic()));
    ElectLeadersResponseData response = new ElectLeadersResponseData().setErrorCode(topLevelError.code());
    errorsByTopic.forEach((topic, partitionErrors) -> {
        ReplicaElectionResult electionResult = new ReplicaElectionResult().setTopic(topic);
        electionResult.setPartitionResult(partitionErrors.stream().filter(entry -> !electAllPartitions || entry.getValue().error() != ELECTION_NOT_NEEDED).map(entry -> {
            TopicPartition topicPartition = entry.getKey();
            ApiError error = entry.getValue();
            return new PartitionResult().setPartitionId(topicPartition.partition()).setErrorCode(error.error().code()).setErrorMessage(error.message());
        }).collect(Collectors.toList()));
        response.replicaElectionResults().add(electionResult);
    });
    return response;
}
Also used : MockTime(org.apache.kafka.common.utils.MockTime) TopicPartitionsCollection(org.apache.kafka.common.message.ElectLeadersRequestData.TopicPartitionsCollection) ListPartitionReassignmentsTopics(org.apache.kafka.common.message.ListPartitionReassignmentsRequestData.ListPartitionReassignmentsTopics) ElectLeadersRequestData(org.apache.kafka.common.message.ElectLeadersRequestData) Collections.singletonList(java.util.Collections.singletonList) StaleBrokerEpochException(org.apache.kafka.common.errors.StaleBrokerEpochException) CreatePartitionsTopic(org.apache.kafka.common.message.CreatePartitionsRequestData.CreatePartitionsTopic) PartitionResult(org.apache.kafka.common.message.ElectLeadersResponseData.PartitionResult) Arrays.asList(java.util.Arrays.asList) LogContext(org.apache.kafka.common.utils.LogContext) Map(java.util.Map) TopicData(org.apache.kafka.common.message.AlterIsrRequestData.TopicData) AlterIsrResponseData(org.apache.kafka.common.message.AlterIsrResponseData) Set(java.util.Set) SnapshotRegistry(org.apache.kafka.timeline.SnapshotRegistry) NO_LEADER(org.apache.kafka.metadata.LeaderConstants.NO_LEADER) UNKNOWN_TOPIC_ID(org.apache.kafka.common.protocol.Errors.UNKNOWN_TOPIC_ID) PartitionChangeRecord(org.apache.kafka.common.metadata.PartitionChangeRecord) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Errors(org.apache.kafka.common.protocol.Errors) CreatableTopicResult(org.apache.kafka.common.message.CreateTopicsResponseData.CreatableTopicResult) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) NO_REASSIGNMENT_IN_PROGRESS(org.apache.kafka.common.protocol.Errors.NO_REASSIGNMENT_IN_PROGRESS) BrokerRegistration(org.apache.kafka.metadata.BrokerRegistration) ArrayList(java.util.ArrayList) FENCED_LEADER_EPOCH(org.apache.kafka.common.protocol.Errors.FENCED_LEADER_EPOCH) ElectionType(org.apache.kafka.common.ElectionType) NONE(org.apache.kafka.common.protocol.Errors.NONE) BrokerHeartbeatReply(org.apache.kafka.metadata.BrokerHeartbeatReply) ELECTION_NOT_NEEDED(org.apache.kafka.common.protocol.Errors.ELECTION_NOT_NEEDED) AlterPartitionReassignmentsRequestData(org.apache.kafka.common.message.AlterPartitionReassignmentsRequestData) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ValueSource(org.junit.jupiter.params.provider.ValueSource) CreatableReplicaAssignment(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableReplicaAssignment) ElectLeadersResponseData(org.apache.kafka.common.message.ElectLeadersResponseData) ReassignablePartition(org.apache.kafka.common.message.AlterPartitionReassignmentsRequestData.ReassignablePartition) BrokerHeartbeatRequestData(org.apache.kafka.common.message.BrokerHeartbeatRequestData) Assertions.assertArrayEquals(org.junit.jupiter.api.Assertions.assertArrayEquals) AtomicLong(java.util.concurrent.atomic.AtomicLong) SEGMENT_BYTES_CONFIG(org.apache.kafka.common.config.TopicConfig.SEGMENT_BYTES_CONFIG) CreatableTopicCollection(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicCollection) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) 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) PartitionData(org.apache.kafka.common.message.AlterIsrRequestData.PartitionData) CreatePartitionsAssignment(org.apache.kafka.common.message.CreatePartitionsRequestData.CreatePartitionsAssignment) POLICY_VIOLATION(org.apache.kafka.common.protocol.Errors.POLICY_VIOLATION) ConfigRecord(org.apache.kafka.common.metadata.ConfigRecord) LoggerFactory(org.slf4j.LoggerFactory) Assertions.assertNotEquals(org.junit.jupiter.api.Assertions.assertNotEquals) CreatePartitionsTopicResult(org.apache.kafka.common.message.CreatePartitionsResponseData.CreatePartitionsTopicResult) SecurityProtocol(org.apache.kafka.common.security.auth.SecurityProtocol) ELIGIBLE_LEADERS_NOT_AVAILABLE(org.apache.kafka.common.protocol.Errors.ELIGIBLE_LEADERS_NOT_AVAILABLE) ReassignableTopicResponse(org.apache.kafka.common.message.AlterPartitionReassignmentsResponseData.ReassignableTopicResponse) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) ReplicaElectionResult(org.apache.kafka.common.message.ElectLeadersResponseData.ReplicaElectionResult) TopicRecord(org.apache.kafka.common.metadata.TopicRecord) TopicPartition(org.apache.kafka.common.TopicPartition) TopicPartitions(org.apache.kafka.common.message.ElectLeadersRequestData.TopicPartitions) INVALID_PARTITIONS(org.apache.kafka.common.protocol.Errors.INVALID_PARTITIONS) PartitionRegistration(org.apache.kafka.metadata.PartitionRegistration) Collectors(java.util.stream.Collectors) Replicas(org.apache.kafka.metadata.Replicas) Test(org.junit.jupiter.api.Test) List(java.util.List) TopicIdPartition(org.apache.kafka.controller.BrokersToIsrs.TopicIdPartition) Optional(java.util.Optional) CreateTopicsResponseData(org.apache.kafka.common.message.CreateTopicsResponseData) INVALID_TOPIC_EXCEPTION(org.apache.kafka.common.protocol.Errors.INVALID_TOPIC_EXCEPTION) Uuid(org.apache.kafka.common.Uuid) IntStream(java.util.stream.IntStream) ReassignablePartitionResponse(org.apache.kafka.common.message.AlterPartitionReassignmentsResponseData.ReassignablePartitionResponse) ListPartitionReassignmentsResponseData(org.apache.kafka.common.message.ListPartitionReassignmentsResponseData) HashMap(java.util.HashMap) CreatableTopic(org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic) OptionalInt(java.util.OptionalInt) ApiError(org.apache.kafka.common.requests.ApiError) HashSet(java.util.HashSet) 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) Collections.singletonMap(java.util.Collections.singletonMap) UNKNOWN_TOPIC_OR_PARTITION(org.apache.kafka.common.protocol.Errors.UNKNOWN_TOPIC_OR_PARTITION) Utils(org.apache.kafka.common.utils.Utils) Logger(org.slf4j.Logger) InvalidReplicaAssignmentException(org.apache.kafka.common.errors.InvalidReplicaAssignmentException) PREFERRED_LEADER_NOT_AVAILABLE(org.apache.kafka.common.protocol.Errors.PREFERRED_LEADER_NOT_AVAILABLE) INVALID_REPLICA_ASSIGNMENT(org.apache.kafka.common.protocol.Errors.INVALID_REPLICA_ASSIGNMENT) TimeUnit(java.util.concurrent.TimeUnit) AlterPartitionReassignmentsResponseData(org.apache.kafka.common.message.AlterPartitionReassignmentsResponseData) CreateTopicPolicy(org.apache.kafka.server.policy.CreateTopicPolicy) AlterIsrRequestData(org.apache.kafka.common.message.AlterIsrRequestData) RegisterBrokerRecord(org.apache.kafka.common.metadata.RegisterBrokerRecord) Timeout(org.junit.jupiter.api.Timeout) Collections(java.util.Collections) TopicPartition(org.apache.kafka.common.TopicPartition) ElectLeadersResponseData(org.apache.kafka.common.message.ElectLeadersResponseData) ReplicaElectionResult(org.apache.kafka.common.message.ElectLeadersResponseData.ReplicaElectionResult) Collections.singletonList(java.util.Collections.singletonList) Arrays.asList(java.util.Arrays.asList) ArrayList(java.util.ArrayList) List(java.util.List) ApiError(org.apache.kafka.common.requests.ApiError) PartitionResult(org.apache.kafka.common.message.ElectLeadersResponseData.PartitionResult) Map(java.util.Map) HashMap(java.util.HashMap) Collections.singletonMap(java.util.Collections.singletonMap)

Example 82 with Errors

use of org.apache.kafka.common.protocol.Errors in project kafka by apache.

the class KafkaRaftClient method handleBeginQuorumEpochResponse.

private boolean handleBeginQuorumEpochResponse(RaftResponse.Inbound responseMetadata, long currentTimeMs) {
    int remoteNodeId = responseMetadata.sourceId();
    BeginQuorumEpochResponseData response = (BeginQuorumEpochResponseData) responseMetadata.data;
    Errors topLevelError = Errors.forCode(response.errorCode());
    if (topLevelError != Errors.NONE) {
        return handleTopLevelError(topLevelError, responseMetadata);
    }
    if (!hasValidTopicPartition(response, log.topicPartition())) {
        return false;
    }
    BeginQuorumEpochResponseData.PartitionData partitionResponse = response.topics().get(0).partitions().get(0);
    Errors partitionError = Errors.forCode(partitionResponse.errorCode());
    OptionalInt responseLeaderId = optionalLeaderId(partitionResponse.leaderId());
    int responseEpoch = partitionResponse.leaderEpoch();
    Optional<Boolean> handled = maybeHandleCommonResponse(partitionError, responseLeaderId, responseEpoch, currentTimeMs);
    if (handled.isPresent()) {
        return handled.get();
    } else if (partitionError == Errors.NONE) {
        if (quorum.isLeader()) {
            LeaderState<T> state = quorum.leaderStateOrThrow();
            state.addAcknowledgementFrom(remoteNodeId);
        } else {
            logger.debug("Ignoring BeginQuorumEpoch response {} since " + "this node is not the leader anymore", response);
        }
        return true;
    } else {
        return handleUnexpectedError(partitionError, responseMetadata);
    }
}
Also used : Errors(org.apache.kafka.common.protocol.Errors) OptionalInt(java.util.OptionalInt) BeginQuorumEpochResponseData(org.apache.kafka.common.message.BeginQuorumEpochResponseData)

Example 83 with Errors

use of org.apache.kafka.common.protocol.Errors in project kafka by apache.

the class KafkaRaftClient method handleFetchResponse.

private boolean handleFetchResponse(RaftResponse.Inbound responseMetadata, long currentTimeMs) {
    FetchResponseData response = (FetchResponseData) responseMetadata.data;
    Errors topLevelError = Errors.forCode(response.errorCode());
    if (topLevelError != Errors.NONE) {
        return handleTopLevelError(topLevelError, responseMetadata);
    }
    if (!RaftUtil.hasValidTopicPartition(response, log.topicPartition(), log.topicId())) {
        return false;
    }
    // If the ID is valid, we can set the topic name.
    response.responses().get(0).setTopic(log.topicPartition().topic());
    FetchResponseData.PartitionData partitionResponse = response.responses().get(0).partitions().get(0);
    FetchResponseData.LeaderIdAndEpoch currentLeaderIdAndEpoch = partitionResponse.currentLeader();
    OptionalInt responseLeaderId = optionalLeaderId(currentLeaderIdAndEpoch.leaderId());
    int responseEpoch = currentLeaderIdAndEpoch.leaderEpoch();
    Errors error = Errors.forCode(partitionResponse.errorCode());
    Optional<Boolean> handled = maybeHandleCommonResponse(error, responseLeaderId, responseEpoch, currentTimeMs);
    if (handled.isPresent()) {
        return handled.get();
    }
    FollowerState state = quorum.followerStateOrThrow();
    if (error == Errors.NONE) {
        FetchResponseData.EpochEndOffset divergingEpoch = partitionResponse.divergingEpoch();
        if (divergingEpoch.epoch() >= 0) {
            // The leader is asking us to truncate before continuing
            final OffsetAndEpoch divergingOffsetAndEpoch = new OffsetAndEpoch(divergingEpoch.endOffset(), divergingEpoch.epoch());
            state.highWatermark().ifPresent(highWatermark -> {
                if (divergingOffsetAndEpoch.offset < highWatermark.offset) {
                    throw new KafkaException("The leader requested truncation to offset " + divergingOffsetAndEpoch.offset + ", which is below the current high watermark" + " " + highWatermark);
                }
            });
            long truncationOffset = log.truncateToEndOffset(divergingOffsetAndEpoch);
            logger.info("Truncated to offset {} from Fetch response from leader {}", truncationOffset, quorum.leaderIdOrSentinel());
        } else if (partitionResponse.snapshotId().epoch() >= 0 || partitionResponse.snapshotId().endOffset() >= 0) {
            if (partitionResponse.snapshotId().epoch() < 0) {
                logger.error("The leader sent a snapshot id with a valid end offset {} but with an invalid epoch {}", partitionResponse.snapshotId().endOffset(), partitionResponse.snapshotId().epoch());
                return false;
            } else if (partitionResponse.snapshotId().endOffset() < 0) {
                logger.error("The leader sent a snapshot id with a valid epoch {} but with an invalid end offset {}", partitionResponse.snapshotId().epoch(), partitionResponse.snapshotId().endOffset());
                return false;
            } else {
                final OffsetAndEpoch snapshotId = new OffsetAndEpoch(partitionResponse.snapshotId().endOffset(), partitionResponse.snapshotId().epoch());
                // Do not validate the snapshot id against the local replicated log
                // since this snapshot is expected to reference offsets and epochs
                // greater than the log end offset and high-watermark
                state.setFetchingSnapshot(log.storeSnapshot(snapshotId));
            }
        } else {
            Records records = FetchResponse.recordsOrFail(partitionResponse);
            if (records.sizeInBytes() > 0) {
                appendAsFollower(records);
            }
            OptionalLong highWatermark = partitionResponse.highWatermark() < 0 ? OptionalLong.empty() : OptionalLong.of(partitionResponse.highWatermark());
            updateFollowerHighWatermark(state, highWatermark);
        }
        state.resetFetchTimeout(currentTimeMs);
        return true;
    } else {
        return handleUnexpectedError(error, responseMetadata);
    }
}
Also used : OptionalInt(java.util.OptionalInt) Errors(org.apache.kafka.common.protocol.Errors) FetchResponseData(org.apache.kafka.common.message.FetchResponseData) OptionalLong(java.util.OptionalLong) KafkaException(org.apache.kafka.common.KafkaException) UnalignedRecords(org.apache.kafka.common.record.UnalignedRecords) MemoryRecords(org.apache.kafka.common.record.MemoryRecords) Records(org.apache.kafka.common.record.Records) UnalignedMemoryRecords(org.apache.kafka.common.record.UnalignedMemoryRecords)

Example 84 with Errors

use of org.apache.kafka.common.protocol.Errors in project kafka by apache.

the class KafkaRaftClient method handleVoteRequest.

/**
 * Handle a Vote request. This API may return the following errors:
 *
 * - {@link Errors#INCONSISTENT_CLUSTER_ID} if the cluster id is presented in request
 *      but different from this node
 * - {@link Errors#BROKER_NOT_AVAILABLE} if this node is currently shutting down
 * - {@link Errors#FENCED_LEADER_EPOCH} if the epoch is smaller than this node's epoch
 * - {@link Errors#INCONSISTENT_VOTER_SET} if the request suggests inconsistent voter membership (e.g.
 *      if this node or the sender is not one of the current known voters)
 * - {@link Errors#INVALID_REQUEST} if the last epoch or offset are invalid
 */
private VoteResponseData handleVoteRequest(RaftRequest.Inbound requestMetadata) {
    VoteRequestData request = (VoteRequestData) requestMetadata.data;
    if (!hasValidClusterId(request.clusterId())) {
        return new VoteResponseData().setErrorCode(Errors.INCONSISTENT_CLUSTER_ID.code());
    }
    if (!hasValidTopicPartition(request, log.topicPartition())) {
        // Until we support multi-raft, we treat individual topic partition mismatches as invalid requests
        return new VoteResponseData().setErrorCode(Errors.INVALID_REQUEST.code());
    }
    VoteRequestData.PartitionData partitionRequest = request.topics().get(0).partitions().get(0);
    int candidateId = partitionRequest.candidateId();
    int candidateEpoch = partitionRequest.candidateEpoch();
    int lastEpoch = partitionRequest.lastOffsetEpoch();
    long lastEpochEndOffset = partitionRequest.lastOffset();
    if (lastEpochEndOffset < 0 || lastEpoch < 0 || lastEpoch >= candidateEpoch) {
        return buildVoteResponse(Errors.INVALID_REQUEST, false);
    }
    Optional<Errors> errorOpt = validateVoterOnlyRequest(candidateId, candidateEpoch);
    if (errorOpt.isPresent()) {
        return buildVoteResponse(errorOpt.get(), false);
    }
    if (candidateEpoch > quorum.epoch()) {
        transitionToUnattached(candidateEpoch);
    }
    OffsetAndEpoch lastEpochEndOffsetAndEpoch = new OffsetAndEpoch(lastEpochEndOffset, lastEpoch);
    boolean voteGranted = quorum.canGrantVote(candidateId, lastEpochEndOffsetAndEpoch.compareTo(endOffset()) >= 0);
    if (voteGranted && quorum.isUnattached()) {
        transitionToVoted(candidateId, candidateEpoch);
    }
    logger.info("Vote request {} with epoch {} is {}", request, candidateEpoch, voteGranted ? "granted" : "rejected");
    return buildVoteResponse(Errors.NONE, voteGranted);
}
Also used : Errors(org.apache.kafka.common.protocol.Errors) VoteResponseData(org.apache.kafka.common.message.VoteResponseData) VoteRequestData(org.apache.kafka.common.message.VoteRequestData)

Example 85 with Errors

use of org.apache.kafka.common.protocol.Errors in project kafka by apache.

the class KafkaRaftClient method tryCompleteFetchRequest.

private FetchResponseData tryCompleteFetchRequest(int replicaId, FetchRequestData.FetchPartition request, long currentTimeMs) {
    try {
        Optional<Errors> errorOpt = validateLeaderOnlyRequest(request.currentLeaderEpoch());
        if (errorOpt.isPresent()) {
            return buildEmptyFetchResponse(errorOpt.get(), Optional.empty());
        }
        long fetchOffset = request.fetchOffset();
        int lastFetchedEpoch = request.lastFetchedEpoch();
        LeaderState<T> state = quorum.leaderStateOrThrow();
        ValidOffsetAndEpoch validOffsetAndEpoch = log.validateOffsetAndEpoch(fetchOffset, lastFetchedEpoch);
        final Records records;
        if (validOffsetAndEpoch.kind() == ValidOffsetAndEpoch.Kind.VALID) {
            LogFetchInfo info = log.read(fetchOffset, Isolation.UNCOMMITTED);
            if (state.updateReplicaState(replicaId, currentTimeMs, info.startOffsetMetadata)) {
                onUpdateLeaderHighWatermark(state, currentTimeMs);
            }
            records = info.records;
        } else {
            records = MemoryRecords.EMPTY;
        }
        return buildFetchResponse(Errors.NONE, records, validOffsetAndEpoch, state.highWatermark());
    } catch (Exception e) {
        logger.error("Caught unexpected error in fetch completion of request {}", request, e);
        return buildEmptyFetchResponse(Errors.UNKNOWN_SERVER_ERROR, Optional.empty());
    }
}
Also used : Errors(org.apache.kafka.common.protocol.Errors) UnalignedRecords(org.apache.kafka.common.record.UnalignedRecords) MemoryRecords(org.apache.kafka.common.record.MemoryRecords) Records(org.apache.kafka.common.record.Records) UnalignedMemoryRecords(org.apache.kafka.common.record.UnalignedMemoryRecords) NotLeaderException(org.apache.kafka.raft.errors.NotLeaderException) NotLeaderOrFollowerException(org.apache.kafka.common.errors.NotLeaderOrFollowerException) KafkaException(org.apache.kafka.common.KafkaException) TimeoutException(java.util.concurrent.TimeoutException) ClusterAuthorizationException(org.apache.kafka.common.errors.ClusterAuthorizationException) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

Errors (org.apache.kafka.common.protocol.Errors)167 HashMap (java.util.HashMap)115 TopicPartition (org.apache.kafka.common.TopicPartition)87 Map (java.util.Map)61 ArrayList (java.util.ArrayList)46 LinkedHashMap (java.util.LinkedHashMap)31 Test (org.junit.jupiter.api.Test)31 List (java.util.List)19 AbstractResponse (org.apache.kafka.common.requests.AbstractResponse)19 HashSet (java.util.HashSet)18 TopicAuthorizationException (org.apache.kafka.common.errors.TopicAuthorizationException)18 InvalidTopicException (org.apache.kafka.common.errors.InvalidTopicException)17 KafkaFutureImpl (org.apache.kafka.common.internals.KafkaFutureImpl)17 MetadataResponse (org.apache.kafka.common.requests.MetadataResponse)17 KafkaException (org.apache.kafka.common.KafkaException)16 Node (org.apache.kafka.common.Node)16 Cluster (org.apache.kafka.common.Cluster)15 OffsetAndMetadata (org.apache.kafka.clients.consumer.OffsetAndMetadata)14 ChannelBuilder (org.apache.kafka.common.network.ChannelBuilder)14 Collections (java.util.Collections)13