Skip to content

Commit 441f506

Browse files
authored
[pebble cache] fix potential buffer leak (#9519)
`NewZstdCompressor` gets a compression buffer from the pool. We must make sure to give that same buffer back to the pool on close. Since `CompressZstd` can allocate a new buffer, we have to track the buffer we got from the pool separately in order to correctly put it back.
1 parent d3df2a7 commit 441f506

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

enterprise/server/backends/pebble_cache/pebble_cache.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2196,8 +2196,9 @@ type zstdCompressor struct {
21962196
cacheName string
21972197

21982198
interfaces.CommittedWriteCloser
2199-
compressBuf []byte
2200-
bufferPool *bytebufferpool.VariableSizePool
2199+
compressBuf []byte
2200+
poolCompressBuf []byte // Buffer we must return to the pool on close.
2201+
bufferPool *bytebufferpool.VariableSizePool
22012202

22022203
numDecompressedBytes int
22032204
numCompressedBytes int
@@ -2209,11 +2210,14 @@ func NewZstdCompressor(cacheName string, wc interfaces.CommittedWriteCloser, bp
22092210
cacheName: cacheName,
22102211
CommittedWriteCloser: wc,
22112212
compressBuf: compressBuf,
2213+
poolCompressBuf: compressBuf,
22122214
bufferPool: bp,
22132215
}
22142216
}
22152217

22162218
func (z *zstdCompressor) Write(decompressedBytes []byte) (int, error) {
2219+
// CompressZstd can allocate a new buffer if the given compressBuf is not large enough
2220+
// to fit the compressed bytes.
22172221
z.compressBuf = compression.CompressZstd(z.compressBuf, decompressedBytes)
22182222
compressedBytesWritten, err := z.CommittedWriteCloser.Write(z.compressBuf)
22192223
if err != nil {
@@ -2233,7 +2237,7 @@ func (z *zstdCompressor) Close() error {
22332237
With(prometheus.Labels{metrics.CompressionType: "zstd", metrics.CacheNameLabel: z.cacheName}).
22342238
Observe(float64(z.numCompressedBytes) / float64(z.numDecompressedBytes))
22352239

2236-
z.bufferPool.Put(z.compressBuf)
2240+
z.bufferPool.Put(z.poolCompressBuf)
22372241
return z.CommittedWriteCloser.Close()
22382242
}
22392243

0 commit comments

Comments
 (0)