Skip to content
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
56e4156
KAFKA-10265 Use the generated messages for FetchRequest and FetchResp…
mumrah Jul 10, 2020
04538af
Fix compile errors and checkstyle
mumrah Jul 10, 2020
6094e4e
Feedback from PR
mumrah Jul 13, 2020
41d03d1
Merge remote-tracking branch 'apache-github/trunk' into KAFKA-9629-fe…
mumrah Jul 13, 2020
5c98083
Fix re-ordering of topic partitions
mumrah Jul 14, 2020
8ca460c
Use generated message class for serialization in FetchRequest also
mumrah Jul 14, 2020
3808a96
Feedback from PR
mumrah Jul 14, 2020
efdadc5
Add jmh benchmarks and fix checkstyle
mumrah Jul 15, 2020
538ed00
Fix sizeOf for records in message class generator
mumrah Jul 16, 2020
155621b
Don't re-create the whole message on static size method
mumrah Jul 16, 2020
89de508
Update benchmarks
mumrah Jul 16, 2020
7878289
Pull up readRecords and writeRecords out of the base interfaces
mumrah Jul 17, 2020
701619d
Add a struct -> message benchmark
mumrah Jul 17, 2020
82a0d46
Merge remote-tracking branch 'apache-github/trunk' into KAFKA-9629-fe…
mumrah Jul 17, 2020
38b2ebf
Re-add storage error conversion logic
mumrah Jul 17, 2020
efa5450
Use ByteBufferOutputStream for auto-resizing buffer in RecordsWriter
mumrah Jul 18, 2020
2514f5a
Remove some TODOs
mumrah Jul 18, 2020
e198797
Clean up and comment ByteBuffer usage
mumrah Jul 20, 2020
cf3bf33
Allocated a larger initial buffer for FetchResponse and grow it at 2x
mumrah Jul 21, 2020
78cd012
Use ByteBuffer with a single allocation
mumrah Jul 23, 2020
507eb04
PR feedback
mumrah Jul 29, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions checkstyle/import-control.xml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@
<subpackage name="protocol">
<allow pkg="org.apache.kafka.common.errors" />
<allow pkg="org.apache.kafka.common.message" />
<allow pkg="org.apache.kafka.common.network" />
<allow pkg="org.apache.kafka.common.protocol" />
<allow pkg="org.apache.kafka.common.protocol.types" />
<allow pkg="org.apache.kafka.common.record" />
Expand Down
2 changes: 2 additions & 0 deletions checkstyle/suppressions.xml
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,8 @@
<suppress checks="(NPathComplexity|ClassFanOutComplexity|CyclomaticComplexity|ClassDataAbstractionCoupling|FinalLocalVariable|LocalVariableName|MemberName|ParameterName|MethodLength|JavaNCSS)"
files="streams[\\/]src[\\/](generated|generated-test)[\\/].+.java$"/>

<suppress checks="ImportControl" files="FetchResponseData.java"/>

<!-- Streams tests -->
<suppress checks="ClassFanOutComplexity"
files="StreamThreadTest.java"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ public void onSuccess(ClientResponse resp) {
log.debug("Fetch {} at offset {} for partition {} returned fetch data {}",
isolationLevel, fetchOffset, partition, partitionData);

Iterator<? extends RecordBatch> batches = partitionData.records.batches().iterator();
Iterator<? extends RecordBatch> batches = partitionData.records().batches().iterator();
short responseVersion = resp.requestHeader().apiVersion();

completedFetches.add(new CompletedFetch(partition, partitionData,
Expand Down Expand Up @@ -616,7 +616,7 @@ public Map<TopicPartition, List<ConsumerRecord<K, V>>> fetchedRecords() {
// in cases such as the TopicAuthorizationException, and the second condition ensures that no
// potential data loss due to an exception in a following record.
FetchResponse.PartitionData partition = records.partitionData;
if (fetched.isEmpty() && (partition.records == null || partition.records.sizeInBytes() == 0)) {
if (fetched.isEmpty() && (partition.records() == null || partition.records().sizeInBytes() == 0)) {
completedFetches.poll();
}
throw e;
Expand Down Expand Up @@ -1210,7 +1210,7 @@ private CompletedFetch initializeCompletedFetch(CompletedFetch nextCompletedFetc
FetchResponse.PartitionData<Records> partition = nextCompletedFetch.partitionData;
long fetchOffset = nextCompletedFetch.nextFetchOffset;
CompletedFetch completedFetch = null;
Errors error = partition.error;
Errors error = partition.error();

try {
if (!subscriptions.hasValidPosition(tp)) {
Expand All @@ -1227,11 +1227,11 @@ private CompletedFetch initializeCompletedFetch(CompletedFetch nextCompletedFetc
}

log.trace("Preparing to read {} bytes of data for partition {} with offset {}",
partition.records.sizeInBytes(), tp, position);
Iterator<? extends RecordBatch> batches = partition.records.batches().iterator();
partition.records().sizeInBytes(), tp, position);
Iterator<? extends RecordBatch> batches = partition.records().batches().iterator();
completedFetch = nextCompletedFetch;

if (!batches.hasNext() && partition.records.sizeInBytes() > 0) {
if (!batches.hasNext() && partition.records().sizeInBytes() > 0) {
if (completedFetch.responseVersion < 3) {
// Implement the pre KIP-74 behavior of throwing a RecordTooLargeException.
Map<TopicPartition, Long> recordTooLargePartitions = Collections.singletonMap(tp, fetchOffset);
Expand All @@ -1249,26 +1249,26 @@ private CompletedFetch initializeCompletedFetch(CompletedFetch nextCompletedFetc
}
}

if (partition.highWatermark >= 0) {
log.trace("Updating high watermark for partition {} to {}", tp, partition.highWatermark);
subscriptions.updateHighWatermark(tp, partition.highWatermark);
if (partition.highWatermark() >= 0) {
log.trace("Updating high watermark for partition {} to {}", tp, partition.highWatermark());
subscriptions.updateHighWatermark(tp, partition.highWatermark());
}

if (partition.logStartOffset >= 0) {
log.trace("Updating log start offset for partition {} to {}", tp, partition.logStartOffset);
subscriptions.updateLogStartOffset(tp, partition.logStartOffset);
if (partition.logStartOffset() >= 0) {
log.trace("Updating log start offset for partition {} to {}", tp, partition.logStartOffset());
subscriptions.updateLogStartOffset(tp, partition.logStartOffset());
}

if (partition.lastStableOffset >= 0) {
log.trace("Updating last stable offset for partition {} to {}", tp, partition.lastStableOffset);
subscriptions.updateLastStableOffset(tp, partition.lastStableOffset);
if (partition.lastStableOffset() >= 0) {
log.trace("Updating last stable offset for partition {} to {}", tp, partition.lastStableOffset());
subscriptions.updateLastStableOffset(tp, partition.lastStableOffset());
}

if (partition.preferredReadReplica.isPresent()) {
subscriptions.updatePreferredReadReplica(completedFetch.partition, partition.preferredReadReplica.get(), () -> {
if (partition.preferredReadReplica().isPresent()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: could probably change this to use ifPresent

subscriptions.updatePreferredReadReplica(completedFetch.partition, partition.preferredReadReplica().get(), () -> {
long expireTimeMs = time.milliseconds() + metadata.metadataExpireMs();
log.debug("Updating preferred read replica for partition {} to {}, set to expire at {}",
tp, partition.preferredReadReplica.get(), expireTimeMs);
tp, partition.preferredReadReplica().get(), expireTimeMs);
return expireTimeMs;
});
}
Expand Down Expand Up @@ -1630,13 +1630,13 @@ private boolean isBatchAborted(RecordBatch batch) {
}

private PriorityQueue<FetchResponse.AbortedTransaction> abortedTransactions(FetchResponse.PartitionData<?> partition) {
if (partition.abortedTransactions == null || partition.abortedTransactions.isEmpty())
if (partition.abortedTransactions() == null || partition.abortedTransactions().isEmpty())
return null;

PriorityQueue<FetchResponse.AbortedTransaction> abortedTransactions = new PriorityQueue<>(
partition.abortedTransactions.size(), Comparator.comparingLong(o -> o.firstOffset)
partition.abortedTransactions().size(), Comparator.comparingLong(o -> o.firstOffset)
);
abortedTransactions.addAll(partition.abortedTransactions);
abortedTransactions.addAll(partition.abortedTransactions());
return abortedTransactions;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@
import org.apache.kafka.common.message.EndTxnResponseData;
import org.apache.kafka.common.message.ExpireDelegationTokenRequestData;
import org.apache.kafka.common.message.ExpireDelegationTokenResponseData;
import org.apache.kafka.common.message.FetchRequestData;
import org.apache.kafka.common.message.FetchResponseData;
import org.apache.kafka.common.message.FindCoordinatorRequestData;
import org.apache.kafka.common.message.FindCoordinatorResponseData;
import org.apache.kafka.common.message.HeartbeatRequestData;
Expand Down Expand Up @@ -114,8 +116,6 @@
import org.apache.kafka.common.protocol.types.Struct;
import org.apache.kafka.common.protocol.types.Type;
import org.apache.kafka.common.record.RecordBatch;
import org.apache.kafka.common.requests.FetchRequest;
import org.apache.kafka.common.requests.FetchResponse;
import org.apache.kafka.common.requests.ListOffsetRequest;
import org.apache.kafka.common.requests.ListOffsetResponse;
import org.apache.kafka.common.requests.OffsetsForLeaderEpochRequest;
Expand All @@ -137,7 +137,7 @@
*/
public enum ApiKeys {
PRODUCE(0, "Produce", ProduceRequest.schemaVersions(), ProduceResponse.schemaVersions()),
FETCH(1, "Fetch", FetchRequest.schemaVersions(), FetchResponse.schemaVersions()),
FETCH(1, "Fetch", FetchRequestData.SCHEMAS, FetchResponseData.SCHEMAS),
LIST_OFFSETS(2, "ListOffsets", ListOffsetRequest.schemaVersions(), ListOffsetResponse.schemaVersions()),
METADATA(3, "Metadata", MetadataRequestData.SCHEMAS, MetadataResponseData.SCHEMAS),
LEADER_AND_ISR(4, "LeaderAndIsr", true, LeaderAndIsrRequestData.SCHEMAS, LeaderAndIsrResponseData.SCHEMAS),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.kafka.common.protocol;

import org.apache.kafka.common.record.BaseRecords;
import org.apache.kafka.common.record.MemoryRecords;
import org.apache.kafka.common.utils.ByteUtils;

import java.nio.ByteBuffer;

/**
* Implementation of Readable which reads from a byte buffer and can read records as {@link MemoryRecords}
*
* @see org.apache.kafka.common.requests.FetchResponse
*/
public class RecordsReader implements Readable {
Comment thread
hachikuji marked this conversation as resolved.
Outdated
private final ByteBuffer buf;

public RecordsReader(ByteBuffer buf) {
this.buf = buf;
}

@Override
public byte readByte() {
return buf.get();
}

@Override
public short readShort() {
return buf.getShort();
}

@Override
public int readInt() {
return buf.getInt();
}

@Override
public long readLong() {
return buf.getLong();
}

@Override
public double readDouble() {
return ByteUtils.readDouble(buf);
}

@Override
public void readArray(byte[] arr) {
buf.get(arr);
}

@Override
public int readUnsignedVarint() {
return ByteUtils.readUnsignedVarint(buf);
}

@Override
public ByteBuffer readByteBuffer(int length) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More of a side question, but is this length guaranteed to be less than the buffer size? Wondering if it is worth adding range checking.

@mumrah mumrah Jul 29, 2020

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is copied straight from ByteBufferAccessor and will probably go away in a follow-on PR. But either way, looking at it it seems it should always be in range since this is used by zero-copy byte fields in the message classes, e.g.

int len = _reader.readInt();
if (len > 0) {
  this.someZeroCopyField = _reader.readByteBuffer(len);
}

So generally it's probably safe. In the case of a corrupt message where the length is wrong, ByteBuffer#limit will throw an error and parsing will fail. It probably would be nice to put a range check in ByteBufferAccessor so we can throw a more useful error.

ByteBuffer res = buf.slice();
res.limit(length);

buf.position(buf.position() + length);

return res;
}

public BaseRecords readRecords(int length) {
if (length < 0) {
// no records
return null;
} else {
ByteBuffer recordsBuffer = readByteBuffer(length);
return MemoryRecords.readableRecords(recordsBuffer);
}
}
}
Loading