Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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 @@ -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
Expand Up @@ -18,6 +18,7 @@
package org.apache.kafka.common.protocol;

import org.apache.kafka.common.protocol.types.RawTaggedField;
import org.apache.kafka.common.record.BaseRecords;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
Expand All @@ -35,6 +36,10 @@ public interface Readable {
int readUnsignedVarint();
ByteBuffer readByteBuffer(int length);

default BaseRecords readRecords(int length) {
throw new UnsupportedOperationException("Not implemented");
}
Comment thread
mumrah marked this conversation as resolved.
Outdated

default String readString(int length) {
byte[] arr = new byte[length];
readArray(arr);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* 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;
}

@Override
public BaseRecords readRecords(int length) {
if (length < 0) {
// no records
return null;
} else {
ByteBuffer recordsBuffer = readByteBuffer(length);
return MemoryRecords.readableRecords(recordsBuffer);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/*
* 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.network.ByteBufferSend;
import org.apache.kafka.common.network.Send;
import org.apache.kafka.common.record.BaseRecords;
import org.apache.kafka.common.utils.ByteUtils;

import java.io.ByteArrayOutputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.function.Consumer;

/**
* Implementation of Writable which produces a sequence of {@link Send} objects. This allows for deferring the transfer
* of data from a record-set's file channel to the eventual socket channel.
*
* Excepting {@link #writeRecords(BaseRecords)}, calls to the write methods on this class will append to a byte array
* according to the format specified in {@link DataOutput}. When a call is made to writeRecords, any previously written
* bytes will be flushed as a new {@link ByteBufferSend} to the given Send consumer. After flushing the pending bytes,
* another Send is passed to the consumer which wraps the underlying record-set's transfer logic.
*
* For example,
*
* <pre>
* recordsWritable.writeInt(10);
* recordsWritable.writeRecords(records1);
* recordsWritable.writeInt(20);
* recordsWritable.writeRecords(records2);
* recordsWritable.writeInt(30);
* recordsWritable.flush();
* </pre>
*
* Will pass 5 Send objects to the consumer given in the constructor. Care must be taken by callers to flush any
* pending bytes at the end of the writing sequence to ensure everything is flushed to the consumer. This class is
* intended to be used with {@link org.apache.kafka.common.record.MultiRecordsSend}.
*
* @see org.apache.kafka.common.requests.FetchResponse
*/
public class RecordsWriter implements Writable {
Comment thread
mumrah marked this conversation as resolved.
Outdated
private final String dest;
private final Consumer<Send> sendConsumer;
private final ByteArrayOutputStream byteArrayOutputStream;
private final DataOutput output;

public RecordsWriter(String dest, Consumer<Send> sendConsumer) {
this.dest = dest;
this.sendConsumer = sendConsumer;
this.byteArrayOutputStream = new ByteArrayOutputStream();
this.output = new DataOutputStream(this.byteArrayOutputStream);
}

@Override
public void writeByte(byte val) {
writeQuietly(() -> output.writeByte(val));
Comment thread
mumrah marked this conversation as resolved.
Outdated
}

@Override
public void writeShort(short val) {
writeQuietly(() -> output.writeShort(val));
}

@Override
public void writeInt(int val) {
writeQuietly(() -> output.writeInt(val));
}

@Override
public void writeLong(long val) {
writeQuietly(() -> output.writeLong(val));

}

@Override
public void writeDouble(double val) {
writeQuietly(() -> ByteUtils.writeDouble(val, output));

}

@Override
public void writeByteArray(byte[] arr) {
writeQuietly(() -> output.write(arr));
}

@Override
public void writeUnsignedVarint(int i) {
writeQuietly(() -> ByteUtils.writeUnsignedVarint(i, output));
}

@Override
public void writeByteBuffer(ByteBuffer src) {
writeQuietly(() -> output.write(src.array(), src.position(), src.remaining()));
}

@FunctionalInterface
private interface IOExceptionThrowingRunnable {
void run() throws IOException;
}

private void writeQuietly(IOExceptionThrowingRunnable runnable) {
try {
runnable.run();
} catch (IOException e) {
throw new RuntimeException("Writable encountered an IO error", e);
}
}

@Override
public void writeRecords(BaseRecords records) {
flush();
sendConsumer.accept(records.toSend(dest));
}

/**
* Flush any pending bytes as a ByteBufferSend and reset the buffer
*/
public void flush() {
ByteBufferSend send = new ByteBufferSend(dest,
ByteBuffer.wrap(byteArrayOutputStream.toByteArray()));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This creates a copy of the underlying bytes, can we avoid it?

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.

Yea, it's possible, but rather complicated I think. We would need to manage our own byte array and grow it on-demand (like what happens in ByteArrayOutputStream). Then we could use ByteBuffer#slice to pass views of this array to the ByteBufferSend objects. I don't think this current approach is any worse than before in terms of array allocations, so maybe we could save this for a future optimization?

@ijuma ijuma Jul 17, 2020

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Would org.apache.kafka.common.utils.ByteBufferOutputStream be useful here?

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.

Looks like the expansion factor for ByteArrayOutputStream varies on the JDK version. In JDK 8 and 11 it's 2x, but in JDK 14 it just grows the buffer to the minimum needed size.

Our growth factor of 1.1 in ByteBufferOutputStream seems reasonable . Not to mention avoiding the final copy by using slice would be nice too.

@ijuma ijuma Jul 20, 2020

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@mumrah Thanks for checking this. However, the behavior in JDK 14 has not changed in that way. Performance would be atrocious if it did:

private void ensureCapacity(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = buf.length;
        int minGrowth = minCapacity - oldCapacity;
        if (minGrowth > 0) {
            buf = Arrays.copyOf(buf, ArraysSupport.newLength(oldCapacity,
                    minGrowth, oldCapacity /* preferred growth */));
        }

The third parameter passed to newLength is the preferred growth, which is oldCapacity. That is, it doubles if it doesn't cause overflow. We should probably double for ByteBufferOutputStream too if we have no estimate of the expected size. 1.1 growth makes sense if we do have a reasonable estimate (which is the case in current usage, I believe, but perhaps not in this case).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looking a bit more, it seems like this will be mostly used by the data that precedes the actual records. Do we have a sense for what's the typical size for that? If we do, we can use that in the initial size and we can keep the 1.1 growth.

@mumrah mumrah Jul 20, 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.

Thanks for the explanation, @ijuma. I missed the semantics of newLength

After the initial few top-level fields, each partition will have something like 38 bytes preceding its records (at a minimum, aborted transactions could increase that). Maybe we could increase initial capacity to 64 bytes?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Sounds good.

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.

I increased the initial buffer size to 64 and also added 2x growth factor for the buffer. It occurred to me the initial size only really helps for the first partition's header fields, but beyond that (since we are reusing/growing the same ByteBufferOutputStream) we don't know what we'll need. The JMH benchmark did confirm that 2x was more performant than 1.1x for FetchResponse.

Existing usages of ByteBufferOutputStream were not modified and still use 1.1x

sendConsumer.accept(send);
byteArrayOutputStream.reset();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

package org.apache.kafka.common.protocol;

import org.apache.kafka.common.record.BaseRecords;

import java.nio.ByteBuffer;
import java.util.UUID;

Expand All @@ -30,6 +32,10 @@ public interface Writable {
void writeUnsignedVarint(int i);
void writeByteBuffer(ByteBuffer buf);

default void writeRecords(BaseRecords records) {
throw new UnsupportedOperationException("Not implemented");
}

default void writeUUID(UUID uuid) {
writeLong(uuid.getMostSignificantBits());
writeLong(uuid.getLeastSignificantBits());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package org.apache.kafka.common.requests;

import org.apache.kafka.common.errors.UnsupportedVersionException;
import org.apache.kafka.common.message.FetchRequestData;
import org.apache.kafka.common.network.NetworkSend;
import org.apache.kafka.common.network.Send;
import org.apache.kafka.common.protocol.ApiKeys;
Expand Down Expand Up @@ -146,7 +147,7 @@ public static AbstractRequest parseRequest(ApiKeys apiKey, short apiVersion, Str
case PRODUCE:
return new ProduceRequest(struct, apiVersion);
case FETCH:
return new FetchRequest(struct, apiVersion);
return new FetchRequest(new FetchRequestData(struct, apiVersion), apiVersion);

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: any reason not to stick with the same constructor convention as the other requests?

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.

I just wanted to remove the Struct constructor of FetchRequest completely. Eventually, RequestContext#parseRequest(ByteBuffer) will stop using Structs and pass the message data classes to AbstractRequest#parseRequest (or similar).

case LIST_OFFSETS:
return new ListOffsetRequest(struct, apiVersion);
case METADATA:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,16 @@
*/
package org.apache.kafka.common.requests;

import org.apache.kafka.common.protocol.ApiMessage;

public interface AbstractRequestResponse {
/**
* Return the auto-generated `Message` instance if this request/response relies on one for
* serialization/deserialization. If this class has not yet been updated to rely on the auto-generated protocol
* classes, return `null`.
* @return
*/
default ApiMessage data() {

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.

Is there an advantage to pulling this up? Seems like we still need to update a bunch more classes. Until we have all the protocols converted, it might be safer to find another approach.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I have a PR that does need. I really need to get that over the line.

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.

Perhaps instead we could add this to a mixin type. Then if we find cases where getting accessing to the ApiMessage generally would be useful, we could just use instanceof checks. These would ultimately go away after the conversions are finished.

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.

@mumrah Do we need this for this PR or can we leave this for #7409?

return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/
package org.apache.kafka.common.requests;

import org.apache.kafka.common.message.FetchResponseData;
import org.apache.kafka.common.network.NetworkSend;
import org.apache.kafka.common.network.Send;
import org.apache.kafka.common.protocol.ApiKeys;
Expand Down Expand Up @@ -89,7 +90,7 @@ public static AbstractResponse parseResponse(ApiKeys apiKey, Struct struct, shor
case PRODUCE:
return new ProduceResponse(struct);
case FETCH:
return FetchResponse.parse(struct);
return new FetchResponse<>(new FetchResponseData(struct, version));
case LIST_OFFSETS:
return new ListOffsetResponse(struct);
case METADATA:
Expand Down
Loading