Search in sources :

Example 1 with OffsetForEpochResult

use of org.apache.kafka.clients.consumer.internals.OffsetsForLeaderEpochClient.OffsetForEpochResult in project kafka by apache.

the class Fetcher method validateOffsetsAsync.

/**
 * For each partition which needs validation, make an asynchronous request to get the end-offsets for the partition
 * with the epoch less than or equal to the epoch the partition last saw.
 *
 * Requests are grouped by Node for efficiency.
 */
private void validateOffsetsAsync(Map<TopicPartition, FetchPosition> partitionsToValidate) {
    final Map<Node, Map<TopicPartition, FetchPosition>> regrouped = regroupFetchPositionsByLeader(partitionsToValidate);
    long nextResetTimeMs = time.milliseconds() + requestTimeoutMs;
    regrouped.forEach((node, fetchPositions) -> {
        if (node.isEmpty()) {
            metadata.requestUpdate();
            return;
        }
        NodeApiVersions nodeApiVersions = apiVersions.get(node.idString());
        if (nodeApiVersions == null) {
            client.tryConnect(node);
            return;
        }
        if (!hasUsableOffsetForLeaderEpochVersion(nodeApiVersions)) {
            log.debug("Skipping validation of fetch offsets for partitions {} since the broker does not " + "support the required protocol version (introduced in Kafka 2.3)", fetchPositions.keySet());
            for (TopicPartition partition : fetchPositions.keySet()) {
                subscriptions.completeValidation(partition);
            }
            return;
        }
        subscriptions.setNextAllowedRetry(fetchPositions.keySet(), nextResetTimeMs);
        RequestFuture<OffsetForEpochResult> future = offsetsForLeaderEpochClient.sendAsyncRequest(node, fetchPositions);
        future.addListener(new RequestFutureListener<OffsetForEpochResult>() {

            @Override
            public void onSuccess(OffsetForEpochResult offsetsResult) {
                List<SubscriptionState.LogTruncation> truncations = new ArrayList<>();
                if (!offsetsResult.partitionsToRetry().isEmpty()) {
                    subscriptions.setNextAllowedRetry(offsetsResult.partitionsToRetry(), time.milliseconds() + retryBackoffMs);
                    metadata.requestUpdate();
                }
                // For each OffsetsForLeader response, check if the end-offset is lower than our current offset
                // for the partition. If so, it means we have experienced log truncation and need to reposition
                // that partition's offset.
                // 
                // In addition, check whether the returned offset and epoch are valid. If not, then we should reset
                // its offset if reset policy is configured, or throw out of range exception.
                offsetsResult.endOffsets().forEach((topicPartition, respEndOffset) -> {
                    FetchPosition requestPosition = fetchPositions.get(topicPartition);
                    Optional<SubscriptionState.LogTruncation> truncationOpt = subscriptions.maybeCompleteValidation(topicPartition, requestPosition, respEndOffset);
                    truncationOpt.ifPresent(truncations::add);
                });
                if (!truncations.isEmpty()) {
                    maybeSetOffsetForLeaderException(buildLogTruncationException(truncations));
                }
            }

            @Override
            public void onFailure(RuntimeException e) {
                subscriptions.requestFailed(fetchPositions.keySet(), time.milliseconds() + retryBackoffMs);
                metadata.requestUpdate();
                if (!(e instanceof RetriableException)) {
                    maybeSetOffsetForLeaderException(e);
                }
            }
        });
    });
}
Also used : ListOffsetsRequest(org.apache.kafka.common.requests.ListOffsetsRequest) SerializationException(org.apache.kafka.common.errors.SerializationException) PriorityQueue(java.util.PriorityQueue) LogTruncationException(org.apache.kafka.clients.consumer.LogTruncationException) KafkaException(org.apache.kafka.common.KafkaException) OffsetResetStrategy(org.apache.kafka.clients.consumer.OffsetResetStrategy) ControlRecordType(org.apache.kafka.common.record.ControlRecordType) ByteBuffer(java.nio.ByteBuffer) FetchResponseData(org.apache.kafka.common.message.FetchResponseData) Record(org.apache.kafka.common.record.Record) Cluster(org.apache.kafka.common.Cluster) BufferSupplier(org.apache.kafka.common.utils.BufferSupplier) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RecordBatch(org.apache.kafka.common.record.RecordBatch) ListOffsetsResponse(org.apache.kafka.common.requests.ListOffsetsResponse) LogContext(org.apache.kafka.common.utils.LogContext) Map(java.util.Map) MetricName(org.apache.kafka.common.MetricName) FetchResponse(org.apache.kafka.common.requests.FetchResponse) TimestampType(org.apache.kafka.common.record.TimestampType) Value(org.apache.kafka.common.metrics.stats.Value) MessageFormatter(org.slf4j.helpers.MessageFormatter) TopicPartition(org.apache.kafka.common.TopicPartition) Sensor(org.apache.kafka.common.metrics.Sensor) Time(org.apache.kafka.common.utils.Time) Collection(java.util.Collection) RecordDeserializationException(org.apache.kafka.common.errors.RecordDeserializationException) InvalidTopicException(org.apache.kafka.common.errors.InvalidTopicException) Set(java.util.Set) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) PartitionInfo(org.apache.kafka.common.PartitionInfo) OffsetAndTimestamp(org.apache.kafka.clients.consumer.OffsetAndTimestamp) Collectors(java.util.stream.Collectors) OffsetForEpochResult(org.apache.kafka.clients.consumer.internals.OffsetsForLeaderEpochClient.OffsetForEpochResult) CloseableIterator(org.apache.kafka.common.utils.CloseableIterator) List(java.util.List) Metrics(org.apache.kafka.common.metrics.Metrics) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) OffsetAndMetadata(org.apache.kafka.clients.consumer.OffsetAndMetadata) ListOffsetsTopicResponse(org.apache.kafka.common.message.ListOffsetsResponseData.ListOffsetsTopicResponse) RecordTooLargeException(org.apache.kafka.common.errors.RecordTooLargeException) Errors(org.apache.kafka.common.protocol.Errors) Optional(java.util.Optional) Node(org.apache.kafka.common.Node) FetchRequest(org.apache.kafka.common.requests.FetchRequest) MetadataResponse(org.apache.kafka.common.requests.MetadataResponse) Queue(java.util.Queue) FetchPosition(org.apache.kafka.clients.consumer.internals.SubscriptionState.FetchPosition) ClientResponse(org.apache.kafka.clients.ClientResponse) NodeApiVersions(org.apache.kafka.clients.NodeApiVersions) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Uuid(org.apache.kafka.common.Uuid) Max(org.apache.kafka.common.metrics.stats.Max) Headers(org.apache.kafka.common.header.Headers) Metadata(org.apache.kafka.clients.Metadata) StaleMetadataException(org.apache.kafka.clients.StaleMetadataException) FetchSessionHandler(org.apache.kafka.clients.FetchSessionHandler) HashMap(java.util.HashMap) RetriableException(org.apache.kafka.common.errors.RetriableException) ListOffsetsPartitionResponse(org.apache.kafka.common.message.ListOffsetsResponseData.ListOffsetsPartitionResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) RecordHeaders(org.apache.kafka.common.header.internals.RecordHeaders) MetadataRequest(org.apache.kafka.common.requests.MetadataRequest) ApiVersion(org.apache.kafka.common.message.ApiVersionsResponseData.ApiVersion) Deserializer(org.apache.kafka.common.serialization.Deserializer) OffsetOutOfRangeException(org.apache.kafka.clients.consumer.OffsetOutOfRangeException) Utils(org.apache.kafka.common.utils.Utils) TimeoutException(org.apache.kafka.common.errors.TimeoutException) Logger(org.slf4j.Logger) ListOffsetsPartition(org.apache.kafka.common.message.ListOffsetsRequestData.ListOffsetsPartition) Iterator(java.util.Iterator) ApiKeys(org.apache.kafka.common.protocol.ApiKeys) ApiVersions(org.apache.kafka.clients.ApiVersions) IsolationLevel(org.apache.kafka.common.IsolationLevel) CorruptRecordException(org.apache.kafka.common.errors.CorruptRecordException) WindowedCount(org.apache.kafka.common.metrics.stats.WindowedCount) Avg(org.apache.kafka.common.metrics.stats.Avg) Min(org.apache.kafka.common.metrics.stats.Min) Closeable(java.io.Closeable) TopicAuthorizationException(org.apache.kafka.common.errors.TopicAuthorizationException) Meter(org.apache.kafka.common.metrics.stats.Meter) Gauge(org.apache.kafka.common.metrics.Gauge) ArrayDeque(java.util.ArrayDeque) Comparator(java.util.Comparator) OffsetsForLeaderEpochRequest(org.apache.kafka.common.requests.OffsetsForLeaderEpochRequest) Collections(java.util.Collections) Timer(org.apache.kafka.common.utils.Timer) Optional(java.util.Optional) NodeApiVersions(org.apache.kafka.clients.NodeApiVersions) Node(org.apache.kafka.common.Node) FetchPosition(org.apache.kafka.clients.consumer.internals.SubscriptionState.FetchPosition) TopicPartition(org.apache.kafka.common.TopicPartition) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) OffsetForEpochResult(org.apache.kafka.clients.consumer.internals.OffsetsForLeaderEpochClient.OffsetForEpochResult) RetriableException(org.apache.kafka.common.errors.RetriableException)

Aggregations

Closeable (java.io.Closeable)1 ByteBuffer (java.nio.ByteBuffer)1 ArrayDeque (java.util.ArrayDeque)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 Comparator (java.util.Comparator)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1 Map (java.util.Map)1 Optional (java.util.Optional)1 PriorityQueue (java.util.PriorityQueue)1 Queue (java.util.Queue)1 Set (java.util.Set)1 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1