GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — netty: create adaptive cumulator · grpc/grpc-java@218f772

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • netty/src
    • main/java/io/grpc/netty
      • GrpcHttp2ConnectionHandler.java
      • NettyAdaptiveCumulator.java
    • test/java/io/grpc/netty
      • NettyAdaptiveCumulatorTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎netty/src/main/java/io/grpc/netty/GrpcHttp2ConnectionHandler.java‎

Copy file name to clipboardExpand all lines: netty/src/main/java/io/grpc/netty/GrpcHttp2ConnectionHandler.java
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
*/
3232
@Internal
3333
public abstract class GrpcHttp2ConnectionHandler extends Http2ConnectionHandler {
34+
protected static final int CUMULATOR_COMPOSE_MIN_SIZE = 1024;
3435

3536
@Nullable
3637
protected final ChannelPromise channelUnused;
@@ -42,6 +43,7 @@ protected GrpcHttp2ConnectionHandler(
4243
Http2Settings initialSettings) {
4344
super(decoder, encoder, initialSettings);
4445
this.channelUnused = channelUnused;
46+
setCumulator(new NettyAdaptiveCumulator(CUMULATOR_COMPOSE_MIN_SIZE));
4547
}
4648

4749
/**
Collapse file

‎netty/src/main/java/io/grpc/netty/NettyAdaptiveCumulator.java‎

Copy file name to clipboard
+184Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
/*
2+
* Copyright 2020 The gRPC Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package io.grpc.netty;
18+
19+
import com.google.common.annotations.VisibleForTesting;
20+
import com.google.common.base.Preconditions;
21+
import io.netty.buffer.ByteBuf;
22+
import io.netty.buffer.ByteBufAllocator;
23+
import io.netty.buffer.CompositeByteBuf;
24+
25+
class NettyAdaptiveCumulator implements io.netty.handler.codec.ByteToMessageDecoder.Cumulator {
26+
private final int composeMinSize;
27+
28+
NettyAdaptiveCumulator(int composeMinSize) {
29+
Preconditions.checkArgument(composeMinSize >= 0, "composeMinSize must be non-negative");
30+
this.composeMinSize = composeMinSize;
31+
}
32+
33+
/**
34+
* "Adaptive" cumulator: cumulate {@link ByteBuf}s by dynamically switching between merge and
35+
* compose strategies.
36+
*
37+
* <p>This cumulator applies a heuristic to make a decision whether to track a reference to the
38+
* buffer with bytes received from the network stack in an array ("zero-copy"), or to merge it
39+
* with merge into the last component (the tail) and appending the incoming buffer by performing
40+
* memory copy.
41+
*
42+
* <p>It is necessary as a protection from a potential attack on the {@link
43+
* io.netty.handler.codec.ByteToMessageDecoder#COMPOSITE_CUMULATOR}. Consider a pathological case
44+
* when an attacker sends TCP packages containing a single byte of data, and forcing cumulator to
45+
* track each one in a separate buffer. The cost is memory overhead for each buffer, as well as
46+
* extra compute to read the cumulation.
47+
*
48+
* <p>Implemented heuristic establishes minimal threshold for the total size of the tail and
49+
* incoming buffer, below which they are merged. The sum of the tail and the incoming buffer is
50+
* used to avoid a case where attacker alternates the size of data packets to trick the cumulator
51+
* into always selecting compose strategy.
52+
*
53+
* <p>The merging strategy attempts to minimize unnecessary memory writes. When possible, it
54+
* expands the tail capacity and only copies the incoming buffer into available memory. Otherwise,
55+
* when both tail and the buffer must be copied, the tail is reallocated (or fully replaced) with
56+
* a new buffer of exponentially increasing capacity (bounded to minComposeSize) to ensure runtime
57+
* {@code O(n^2)} amortized to {@code O(n)}.
58+
*/
59+
@Override
60+
@SuppressWarnings("ReferenceEquality")
61+
public final ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) {
62+
if (!cumulation.isReadable()) {
63+
cumulation.release();
64+
return in;
65+
}
66+
CompositeByteBuf composite = null;
67+
try {
68+
if (cumulation instanceof CompositeByteBuf && cumulation.refCnt() == 1) {
69+
composite = (CompositeByteBuf) cumulation;
70+
// Writer index must equal capacity if we are going to "write"
71+
// new components to the end
72+
if (composite.writerIndex() != composite.capacity()) {
73+
composite.capacity(composite.writerIndex());
74+
}
75+
} else {
76+
composite = alloc.compositeBuffer(Integer.MAX_VALUE)
77+
.addFlattenedComponents(true, cumulation);
78+
}
79+
addInput(alloc, composite, in);
80+
in = null;
81+
return composite;
82+
} finally {
83+
if (in != null) {
84+
// We must release if the ownership was not transferred as otherwise it may produce a leak
85+
in.release();
86+
// Also release any new buffer allocated if we're not returning it
87+
if (composite != null && composite != cumulation) {
88+
composite.release();
89+
}
90+
}
91+
}
92+
}
93+
94+
@VisibleForTesting
95+
void addInput(ByteBufAllocator alloc, CompositeByteBuf composite, ByteBuf in) {
96+
if (shouldCompose(composite, in, composeMinSize)) {
97+
composite.addFlattenedComponents(true, in);
98+
} else {
99+
// The total size of the new data and the last component are below the threshold. Merge them.
100+
mergeWithCompositeTail(alloc, composite, in);
101+
}
102+
}
103+
104+
@VisibleForTesting
105+
static boolean shouldCompose(CompositeByteBuf composite, ByteBuf in, int composeMinSize) {
106+
int componentCount = composite.numComponents();
107+
if (composite.numComponents() == 0) {
108+
return true;
109+
}
110+
int tailSize = composite.capacity() - composite.toByteIndex(componentCount - 1);
111+
return tailSize + in.readableBytes() >= composeMinSize;
112+
}
113+
114+
/**
115+
* Append the given {@link ByteBuf} {@code in} to {@link CompositeByteBuf} {@code composite} by
116+
* expanding or replacing the tail component of the {@link CompositeByteBuf}.
117+
*
118+
* <p>The goal is to prevent {@code O(n^2)} runtime in a pathological case, that forces copying
119+
* the tail component into a new buffer, for each incoming single-byte buffer. We append the new
120+
* bytes to the tail, when a write (or a fast write) is possible.
121+
*
122+
* <p>Otherwise, the tail is replaced with a new buffer, with the capacity increased enough to
123+
* achieve runtime amortization.
124+
*
125+
* <p>We assume that implementations of {@link ByteBufAllocator#calculateNewCapacity(int, int)},
126+
* are similar to {@link io.netty.buffer.AbstractByteBufAllocator#calculateNewCapacity(int, int)},
127+
* which doubles buffer capacity by normalizing it to the closest power of two. This assumption
128+
* is verified in unit tests for this method.
129+
*/
130+
@VisibleForTesting
131+
static void mergeWithCompositeTail(ByteBufAllocator alloc, CompositeByteBuf composite,
132+
ByteBuf in) {
133+
134+
int newBytes = in.readableBytes();
135+
int tailIndex = composite.numComponents() - 1;
136+
int tailStart = composite.toByteIndex(tailIndex);
137+
int tailBytes = composite.capacity() - tailStart;
138+
int totalBytes = newBytes + tailBytes;
139+
140+
ByteBuf tail = composite.component(tailIndex);
141+
ByteBuf merged = null;
142+
143+
try {
144+
if (tail.refCnt() == 1 && !tail.isReadOnly() && totalBytes <= tail.maxCapacity()) {
145+
// Ideal case: the tail isn't shared, and can be expanded to the required capacity.
146+
// Take ownership of the tail.
147+
merged = tail.retainedDuplicate();
148+
merged = merged.unwrap();
149+
// The tail is a readable non-composite buffer, so writeBytes() handles everything for us.
150+
// - ensureWritable() performs a fast resize when possible (f.e. PooledByteBuf's simply
151+
// updates its boundary to the end of consecutive memory run assigned to this buffer)
152+
// - when the required size doesn't fit into maxFastWritableBytes(), a new buffer is
153+
// allocated, and the capacity calculated with alloc.calculateNewCapacity()
154+
merged.writeBytes(in);
155+
} else {
156+
// The tail is shared, or not expandable. Replace it with a new buffer of desired capacity.
157+
merged = alloc.buffer(alloc.calculateNewCapacity(totalBytes, Integer.MAX_VALUE));
158+
merged.setBytes(0, composite, tailStart, tailBytes)
159+
.setBytes(tailBytes, in, in.readerIndex(), newBytes)
160+
.writerIndex(totalBytes);
161+
in.readerIndex(in.writerIndex());
162+
}
163+
// Store readerIndex to avoid out of bounds writerIndex during component replacement.
164+
int prevReader = composite.readerIndex();
165+
// Remove the tail, reset writer index, add merged component.
166+
composite.removeComponent(tailIndex).setIndex(0, tailStart)
167+
.addFlattenedComponents(true, merged);
168+
merged = null;
169+
in.release();
170+
in = null;
171+
// Restore the reader.
172+
composite.readerIndex(prevReader);
173+
} finally {
174+
// Input buffer was merged with the tail.
175+
if (in != null) {
176+
in.release();
177+
}
178+
// If merge's ownership isn't transferred to the composite buf, release it to prevent a leak.
179+
if (merged != null) {
180+
merged.release();
181+
}
182+
}
183+
}
184+
}

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.