Repository navigation
Issue #791: Eliminate byte[] copies in AddEntry code path - #1361
nicmichael wants to merge 4 commits into
Conversation
…f the send buffer before sending it out to bookies, which not only costs CPU cycles for array copying, but also drives up object allocation rate and thus increases young GC frequency.
Currently, the send buffer is prepared by DigestManager.computeDigestAndPackageForSending(), which wraps the netty ByteBuf containing the data together with a (pooled) header buffer into a ByteBufList. So far, we haven't yet allocated or copied any new buffers. But in order to send the buffer to the bookies, PendingAddOp.safeRun() will invoke sendWriteRequest() for each bookie in the write set, which will eventually invoke PerChannelBookieClient.addEntry() for each bookie. In here, we are now allocating two new byte[] and copying the buffer twice per bookie:
byte[] toSendArray = toSend.toArray(); // 1st byte[] allocation and copy
.setBody(ByteString.copyFrom(toSendArray)); // 2nd byte[] allocation and copy
If for example we're using a write set size of 3, then we allocate 6 byte arrays and copy the same buffer 6 times.
The amount of copies can be reduced to just 1 (independent of the write set size) if DigestManager.computeDigestAndPackageForSending() would return a ByteBuf (or ByteBufList) that is backed by an array, which we can access and use without further copying it. PerChannelBookieClient.addEntry() could then wrap this array into a protobuf ByteString without performing any additional copies.
This commit reduces object allocations and array copies to one by:
1. allocating a new (unpooled) array-backed ByteBuf for header, digest, and data in DigestManager.computeDigestAndPackageForSending()
2. copying the data payload into this newly allocated ByteBuf and returning it wrapped into a ByteBufList of size 1 (instead of header + body separately)
3. enhancing ByteBufList to give access to the underlying array if it consists of only a single ByteBuf that's backed by an array
4. extracting the underlying array in PerChannelBookieClient.addEntry() from ByteBufList and wrapping it into protobuf ByteString without copying it.
With this change, only a single byte[] allocation is required (1) and only a single array copy (2). Later steps, in particular step (4), is free of object allocation and array copies.
As a result, the object allocation rate in the AddEntry code path is reduced significantly. In case of a write set size of 3, it is reduced from 6 to 1. This translates into much less frequent young generation garbage collections.
Changes in Rev 2: - Instead of using unpooled heap ByteBuf's, we're now using pooled heap ByteBuf's. For this, we have to instantiate our own PooledByteBufAllocator(false). - DigestManager is now passed a reference to ByteBufAllocator to use for allocations (requires change of constructors of all digest managers). - LedgerHandle passes hint to DigestManager which ByteBufAllocator to use (based on protocol version). - Test classes (not protocol-specific) will automatically use ByteBufAllocator for V3 protocol. For v2 protocol, we keep using pooled direct ByteBufs as before. For v3 protocol, we switch to pooled heap ByteBuf's which are backed by an array. Added API methods to ByteBufList allow us to get a reference to this array and wrap it into a protobuf ByteString without any copies. This reduces (for a write set size of 3) the number of byte[] allocations and copies from 6 to 0. (Rev 1 of this change was reducing them from 6 to 1.)
eolivelli
left a comment
There was a problem hiding this comment.
I like this change.
Great work!
| } | ||
|
|
||
| return ByteBufList.get(headersBuffer, data); | ||
| return ByteBufList.get(sendBuffer); |
There was a problem hiding this comment.
Maybe in a follow up change we can get rid of ByteBufList and use directly the ByteBuf.
Cc @merlimat
There was a problem hiding this comment.
@eolivelli this would make an additional copy of the payload buffer
|
@sijie we can think about cherry picking to 4.7 branch |
sijie
left a comment
There was a problem hiding this comment.
@nicmichael overall looks good. left some comments.
| } | ||
|
|
||
| public static DigestManager instantiate(long ledgerId, byte[] passwd, DigestType digestType, | ||
| boolean useDirectBufferAllocator) throws GeneralSecurityException { |
There was a problem hiding this comment.
I think this is should be useUnpooledBufferAllocator, no? because you can only UnsafeByteOperations over unpooled bytebuf.
There was a problem hiding this comment.
Oh yes, I suppose so. I shouldn't have done that last change and should have stayed with Unpooled. Will revert again.
| * This allocator should be used when using protobuf to eliminate array copies when converting | ||
| * ByteBuf to ByteString. | ||
| */ | ||
| private static final ByteBufAllocator HEAP_BYTEBUF_ALLOCATOR = new PooledByteBufAllocator(false); |
There was a problem hiding this comment.
I think you want need to provide here is an unpooled bytebuf allocator:
There was a problem hiding this comment.
Yes. We can just call Unpooled.buffer() (same as if we instantiate UnpooledByteBufAllocator(false)).
| headersBuffer.writeLong(entryId); | ||
| headersBuffer.writeLong(lastAddConfirmed); | ||
| headersBuffer.writeLong(length); | ||
| ByteBuf sendBuffer = byteBufAllocator.buffer(METADATA_LENGTH + macCodeLength + data.readableBytes()); |
There was a problem hiding this comment.
I think it would be good to keep the original method:
if (useV2Protocol) {
// use the original way
} else {
// use the new way
}
| } | ||
|
|
||
| return ByteBufList.get(headersBuffer, data); | ||
| return ByteBufList.get(sendBuffer); |
| .setMasterKey(ByteString.copyFrom(masterKey)) | ||
| .setBody(ByteString.copyFrom(toSendArray)); | ||
| .setMasterKey(UnsafeByteOperations.unsafeWrap(masterKey)) | ||
| .setBody(toSend.hasArray() |
There was a problem hiding this comment.
this can be:
if (toSend.hasArray) {
UnsafeByteOperations.unsafeWrap(toSend.array(), toSend.arrayOffset(), toSend.readableBytes());
} else if (toSend.size() == 1) { // only one bytebuffer
UnsafeByteOperations.unsafeWrap(toSend.getBuffer(0).nioBuffer());
} else {
UnsafeByteOperations.unsafeWrap(toSend.toArray());
}
|
@eolivelli yes we should cherry-pick this for 4.7.0 |
| // fast path: single copy into existing array | ||
| sendBuffer.writeBytes(data.array(), data.arrayOffset(), data.readableBytes()); | ||
| } else { | ||
| // fall-back to slow path with extra object allocation and copy |
There was a problem hiding this comment.
the logic here seems to be wrong. I think you need to write data into the buffer, no?
any reason why you can't just call sendBuffer.writeBytes(data, data.readerIndex(), data.readableBytes()) to replace line 129-137?
There was a problem hiding this comment.
This "transfers the specified source buffer's data to this buffer". The source is "data", our payload, and the destination is "sendBuffer", the buffer containing header, checksum, and payload. Am I missing something?
But I think we can replace the entire block by
sendBuffer.writeBytes(data);
It will figure out the offset/length itself. The distinction isn't necessary indeed.
There was a problem hiding this comment.
I haven't yet figured out the Netty API and its use in bookkeeper.
It seems to me that writeBytes(ByteBuf src) will consider the source buffers reader index and readableBytes, and according to API doc "This method is basically same with {@link #writeBytes(ByteBuf, int, int)}, except that this method increases the {@code readerIndex} of the source buffer by the number of the transferred bytes while {@link #writeBytes(ByteBuf, int, int)} does not."
I'm not sure whether this difference matters or not... Are we reading from "data" (they payload) elsewhere again? If yes, I suppose we have to use writeBytes(ByteBuf, int, int) instead. Else #writeBytes(ByteBuf) would be just fine, right?
There was a problem hiding this comment.
sendBuffer.writeBytes(data) is basically sendBuffer.writeBytes(data, int, int). writeBytes(data) will modify the readerIndex data. typically the practice is if we don't need to modify the reader/writer index for a bytebuf, try not to modify it. that's much clearer
There was a problem hiding this comment.
Got it, thanks! I just pushed the change to use sendBuffer.writeBytes(data, int, int).
I also verified in the code (and in profiles) that this performs the same as writeBytes(data.array(), data.arrayOffset(), data.readableBytes()) for the case we have a backing array: AbstractByteBuf.writeBytes(...) ends up calling UnpooledHeapByteBuf.setBytes(int index, ByteBuf src, int srcIndex, int length), which checks if (src.hasArray()), and then essentially does the same as what I did manually.
The AddEntry code path in Bookkeeper Client performs several copies of the send buffer before sending it out to bookies, which not only costs CPU cycles for array copying, but also drives up object allocation rate and thus increases young GC frequency.
Currently, the send buffer is prepared by DigestManager.computeDigestAndPackageForSending(), which wraps the netty ByteBuf containing the data together with a (direct) header buffer into a ByteBufList. So far, we haven't yet allocated or copied any new buffers. But in order to send the buffer to the bookies, PendingAddOp.safeRun() will invoke sendWriteRequest() for each bookie in the write set, which will eventually invoke PerChannelBookieClient.addEntry() for each bookie. In here, we are now allocating two new byte[] and copying the buffer twice per bookie for V3 protocol with protobuf:
byte[] toSendArray = toSend.toArray(); // 1st byte[] allocation and copy
.setBody(ByteString.copyFrom(toSendArray)); // 2nd byte[] allocation and copy
If for example we're using a write set size of 3, then we allocate 6 byte arrays and copy the same buffer 6 times.
All 6 copies can be eliminated if DigestManager.computeDigestAndPackageForSending() would return a ByteBuf (or ByteBufList) that is backed by an array, which we can access and use without further copying it. PerChannelBookieClient.addEntry() could then wrap this array into a protobuf ByteString without performing any additional copies.
This change eliminates all byte[] allocations and copies in PCBC by:
1. allocating a new (pooled) array-backed heap ByteBuf for header, digest, and data in DigestManager.computeDigestAndPackageForSending()
2. copying the data payload into this newly allocated ByteBuf and returning it wrapped into a ByteBufList of size 1 (instead of header + body separately)
3. enhancing ByteBufList to give access to the underlying array if it consists of only a single ByteBuf that's backed by an array
4. extracting the underlying array in PerChannelBookieClient.addEntry() from ByteBufList and wrapping it into protobuf ByteString without copying it.
With this change, no more object allocations are required in this code path. DigestManager uses a pooled array (1). We're adding one arraycopy in (2) compared to the original code path, trading this against the allocations and copies we save later on.. Later steps, in particular step (4), is free of object allocation and array copies.
As a result, the object allocation rate in the AddEntry code path is reduced significantly. In case of a write set size of 3, it is reduced from 6 to 0. This translates into much less frequent young generation garbage collections (in my experiments with write-heavy workload by ~4x overall).
Author: Nicolas Michael <[email protected]>
Reviewers: Enrico Olivelli <[email protected]>, Sijie Guo <[email protected]>
This closes #1361 from nicmichael/AddEntryNoCopy, closes #791
(cherry picked from commit e021ac3)
Signed-off-by: Enrico Olivelli <[email protected]>
The AddEntry code path in Bookkeeper Client performs several copies of the send buffer before sending it out to bookies, which not only costs CPU cycles for array copying, but also drives up object allocation rate and thus increases young GC frequency.
Currently, the send buffer is prepared by DigestManager.computeDigestAndPackageForSending(), which wraps the netty ByteBuf containing the data together with a (direct) header buffer into a ByteBufList. So far, we haven't yet allocated or copied any new buffers. But in order to send the buffer to the bookies, PendingAddOp.safeRun() will invoke sendWriteRequest() for each bookie in the write set, which will eventually invoke PerChannelBookieClient.addEntry() for each bookie. In here, we are now allocating two new byte[] and copying the buffer twice per bookie for V3 protocol with protobuf:
byte[] toSendArray = toSend.toArray(); // 1st byte[] allocation and copy
.setBody(ByteString.copyFrom(toSendArray)); // 2nd byte[] allocation and copy
If for example we're using a write set size of 3, then we allocate 6 byte arrays and copy the same buffer 6 times.
All 6 copies can be eliminated if DigestManager.computeDigestAndPackageForSending() would return a ByteBuf (or ByteBufList) that is backed by an array, which we can access and use without further copying it. PerChannelBookieClient.addEntry() could then wrap this array into a protobuf ByteString without performing any additional copies.
This change eliminates all byte[] allocations and copies in PCBC by:
1. allocating a new (pooled) array-backed heap ByteBuf for header, digest, and data in DigestManager.computeDigestAndPackageForSending()
2. copying the data payload into this newly allocated ByteBuf and returning it wrapped into a ByteBufList of size 1 (instead of header + body separately)
3. enhancing ByteBufList to give access to the underlying array if it consists of only a single ByteBuf that's backed by an array
4. extracting the underlying array in PerChannelBookieClient.addEntry() from ByteBufList and wrapping it into protobuf ByteString without copying it.
With this change, no more object allocations are required in this code path. DigestManager uses a pooled array (1). We're adding one arraycopy in (2) compared to the original code path, trading this against the allocations and copies we save later on.. Later steps, in particular step (4), is free of object allocation and array copies.
As a result, the object allocation rate in the AddEntry code path is reduced significantly. In case of a write set size of 3, it is reduced from 6 to 0. This translates into much less frequent young generation garbage collections (in my experiments with write-heavy workload by ~4x overall).
Author: Nicolas Michael <[email protected]>
Reviewers: Enrico Olivelli <[email protected]>, Sijie Guo <[email protected]>
This closes apache#1361 from nicmichael/AddEntryNoCopy, closes apache#791
(cherry picked from commit e021ac3)
The AddEntry code path in Bookkeeper Client performs several copies of the send buffer before sending it out to bookies, which not only costs CPU cycles for array copying, but also drives up object allocation rate and thus increases young GC frequency.
Currently, the send buffer is prepared by DigestManager.computeDigestAndPackageForSending(), which wraps the netty ByteBuf containing the data together with a (direct) header buffer into a ByteBufList. So far, we haven't yet allocated or copied any new buffers. But in order to send the buffer to the bookies, PendingAddOp.safeRun() will invoke sendWriteRequest() for each bookie in the write set, which will eventually invoke PerChannelBookieClient.addEntry() for each bookie. In here, we are now allocating two new byte[] and copying the buffer twice per bookie for V3 protocol with protobuf:
byte[] toSendArray = toSend.toArray(); // 1st byte[] allocation and copy
.setBody(ByteString.copyFrom(toSendArray)); // 2nd byte[] allocation and copy
If for example we're using a write set size of 3, then we allocate 6 byte arrays and copy the same buffer 6 times.
All 6 copies can be eliminated if DigestManager.computeDigestAndPackageForSending() would return a ByteBuf (or ByteBufList) that is backed by an array, which we can access and use without further copying it. PerChannelBookieClient.addEntry() could then wrap this array into a protobuf ByteString without performing any additional copies.
This change eliminates all byte[] allocations and copies in PCBC by:
With this change, no more object allocations are required in this code path. DigestManager uses a pooled array (1). We're adding one arraycopy in (2) compared to the original code path, trading this against the allocations and copies we save later on.. Later steps, in particular step (4), is free of object allocation and array copies.
As a result, the object allocation rate in the AddEntry code path is reduced significantly. In case of a write set size of 3, it is reduced from 6 to 0. This translates into much less frequent young generation garbage collections (in my experiments with write-heavy workload by ~4x overall).