diff --git a/internal/archiver/archiver_test.go b/internal/archiver/archiver_test.go index 312009617..8c51d5c35 100644 --- a/internal/archiver/archiver_test.go +++ b/internal/archiver/archiver_test.go @@ -493,13 +493,17 @@ func (repo *blobCountingSaver) SaveBlob(ctx context.Context, t restic.BlobType, return id, exists, size, err } -func (repo *blobCountingSaver) SaveBlobAsync(ctx context.Context, t restic.BlobType, buf []byte, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, size int, err error)) { +func (repo *blobCountingSaver) SaveBlobAsync(ctx context.Context, t restic.BlobType, buf *restic.BlobBuffer, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, size int, err error)) { repo.saver.SaveBlobAsync(ctx, t, buf, id, storeDuplicate, func(newID restic.ID, known bool, size int, err error) { repo.count(known, restic.BlobHandle{ID: newID, Type: t}) cb(newID, known, size, err) }) } +func (repo *blobCountingSaver) BlobBufferPool() *restic.BlobBufferPool { + return repo.saver.BlobBufferPool() +} + func appendToFile(t testing.TB, filename string, data []byte) { f, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) if err != nil { @@ -2346,7 +2350,7 @@ func (f *failSaveSaver) SaveBlob(ctx context.Context, t restic.BlobType, buf []b return f.saver.SaveBlob(ctx, t, buf, id, storeDuplicate) } -func (f *failSaveSaver) SaveBlobAsync(ctx context.Context, t restic.BlobType, buf []byte, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, size int, err error)) { +func (f *failSaveSaver) SaveBlobAsync(ctx context.Context, t restic.BlobType, buf *restic.BlobBuffer, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, size int, err error)) { // limit concurrency to make test reliable f.semaphore <- struct{}{} @@ -2368,6 +2372,10 @@ func (f *failSaveSaver) SaveBlobAsync(ctx context.Context, t restic.BlobType, bu }) } +func (f *failSaveSaver) BlobBufferPool() *restic.BlobBufferPool { + return f.saver.BlobBufferPool() +} + func TestArchiverAbortEarlyOnError(t *testing.T) { var tests = []struct { src TestDir diff --git a/internal/archiver/buffer.go b/internal/archiver/buffer.go deleted file mode 100644 index 0a6ae6d8f..000000000 --- a/internal/archiver/buffer.go +++ /dev/null @@ -1,47 +0,0 @@ -package archiver - -import "sync" - -// buffer is a reusable buffer. After the buffer has been used, Release should -// be called so the underlying slice is put back into the pool. -type buffer struct { - Data []byte - pool *bufferPool -} - -// Release puts the buffer back into the pool it came from. -func (b *buffer) Release() { - pool := b.pool - if pool == nil || cap(b.Data) > pool.defaultSize { - return - } - - pool.pool.Put(b) -} - -// bufferPool implements a limited set of reusable buffers. -type bufferPool struct { - pool sync.Pool - defaultSize int -} - -// newBufferPool initializes a new buffer pool. The pool stores at most max -// items. New buffers are created with defaultSize. Buffers that have grown -// larger are not put back. -func newBufferPool(defaultSize int) *bufferPool { - b := &bufferPool{ - defaultSize: defaultSize, - } - b.pool = sync.Pool{New: func() any { - return &buffer{ - Data: make([]byte, defaultSize), - pool: b, - } - }} - return b -} - -// Get returns a new buffer, either from the pool or newly allocated. -func (pool *bufferPool) Get() *buffer { - return pool.pool.Get().(*buffer) -} diff --git a/internal/archiver/file_saver.go b/internal/archiver/file_saver.go index f25f3c7b8..ab6a9b32f 100644 --- a/internal/archiver/file_saver.go +++ b/internal/archiver/file_saver.go @@ -18,8 +18,7 @@ const chunkReadBufSize = 512 * 1024 // matches chunker internal read buffer size // fileSaver concurrently saves incoming files to the repo. type fileSaver struct { - saveFilePool *bufferPool - uploader restic.BlobSaverAsync + uploader restic.BlobSaverAsync chunkerFactory restic.ChunkerFactory @@ -38,7 +37,6 @@ func newFileSaver(ctx context.Context, wg *errgroup.Group, uploader restic.BlobS s := &fileSaver{ uploader: uploader, - saveFilePool: newBufferPool(chunkerFactory.MaxChunkSize()), chunkerFactory: chunkerFactory, ch: ch, @@ -224,7 +222,7 @@ func (s *fileSaver) saveFile(ctx context.Context, chnker restic.Chunker, chunkSt node.Size = 0 var idx int for { - buf := s.saveFilePool.Get() + buf := s.uploader.BlobBufferPool().Get() chunkData, err := chunkState.readNextChunk(f, chnker, buf.Data) if err == io.EOF { buf.Release() @@ -239,7 +237,8 @@ func (s *fileSaver) saveFile(ctx context.Context, chnker restic.Chunker, chunkSt // put result buffer back for later reuse buf.Data = chunkData - node.Size += uint64(len(chunkData)) + chunkSize := len(buf.Data) + node.Size += uint64(chunkSize) // test if the context has been cancelled, return the error if ctx.Err() != nil { @@ -256,8 +255,7 @@ func (s *fileSaver) saveFile(ctx context.Context, chnker restic.Chunker, chunkSt node.Content = append(node.Content, restic.ID{}) lock.Unlock() - s.uploader.SaveBlobAsync(ctx, restic.DataBlob, chunkData, restic.ID{}, false, func(newID restic.ID, known bool, sizeInRepo int, err error) { - defer buf.Release() + s.uploader.SaveBlobAsync(ctx, restic.DataBlob, buf, restic.ID{}, false, func(newID restic.ID, known bool, sizeInRepo int, err error) { if err != nil { completeError(err) return @@ -266,7 +264,7 @@ func (s *fileSaver) saveFile(ctx context.Context, chnker restic.Chunker, chunkSt lock.Lock() if !known { fnr.stats.DataBlobs++ - fnr.stats.DataSize += uint64(len(chunkData)) + fnr.stats.DataSize += uint64(chunkSize) fnr.stats.DataSizeInRepo += uint64(sizeInRepo) } node.Content[pos] = newID @@ -283,7 +281,7 @@ func (s *fileSaver) saveFile(ctx context.Context, chnker restic.Chunker, chunkSt return } - s.CompleteBlob(uint64(len(chunkData))) + s.CompleteBlob(uint64(chunkSize)) } err = f.Close() diff --git a/internal/archiver/file_saver_test.go b/internal/archiver/file_saver_test.go index e71bf6cec..2f361c6e1 100644 --- a/internal/archiver/file_saver_test.go +++ b/internal/archiver/file_saver_test.go @@ -11,6 +11,7 @@ import ( "github.com/restic/restic/internal/data" "github.com/restic/restic/internal/fs" "github.com/restic/restic/internal/repository" + "github.com/restic/restic/internal/restic" "github.com/restic/restic/internal/test" "golang.org/x/sync/errgroup" ) @@ -36,7 +37,7 @@ func startFileSaver(ctx context.Context, t testing.TB, _ fs.FS) (*fileSaver, *mo workers := uint(runtime.NumCPU()) chunkerFactory := repository.TestRepository(t).ChunkerFactory() - saver := &mockSaver{saved: make(map[string]int)} + saver := &mockSaver{saved: make(map[string]int), buffers: restic.NewBlobBufferPool(chunkerFactory.MaxChunkSize())} s := newFileSaver(ctx, wg, saver, chunkerFactory, workers) s.NodeFromFileInfo = func(snPath, filename string, meta toNoder, ignoreXattrListError bool) (*data.Node, error) { return meta.ToNode(ignoreXattrListError, t.Logf) diff --git a/internal/archiver/tree_saver.go b/internal/archiver/tree_saver.go index 295a4c393..5473a20c6 100644 --- a/internal/archiver/tree_saver.go +++ b/internal/archiver/tree_saver.go @@ -137,7 +137,7 @@ func (s *treeSaver) save(ctx context.Context, job *saveTreeJob) (*data.Node, Ite ) ch := make(chan struct{}, 1) - s.uploader.SaveBlobAsync(ctx, restic.TreeBlob, buf, restic.ID{}, false, func(newID restic.ID, cbKnown bool, cbSizeInRepo int, cbErr error) { + s.uploader.SaveBlobAsync(ctx, restic.TreeBlob, restic.NewBuffer(buf), restic.ID{}, false, func(newID restic.ID, cbKnown bool, cbSizeInRepo int, cbErr error) { known = cbKnown length = len(buf) sizeInRepo = cbSizeInRepo diff --git a/internal/archiver/tree_saver_test.go b/internal/archiver/tree_saver_test.go index d3ba741c2..fb6bde9a6 100644 --- a/internal/archiver/tree_saver_test.go +++ b/internal/archiver/tree_saver_test.go @@ -15,18 +15,23 @@ import ( ) type mockSaver struct { - saved map[string]int - mutex sync.Mutex + saved map[string]int + mutex sync.Mutex + buffers *restic.BlobBufferPool } -func (m *mockSaver) SaveBlobAsync(_ context.Context, _ restic.BlobType, buf []byte, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, sizeInRepo int, err error)) { +func (m *mockSaver) BlobBufferPool() *restic.BlobBufferPool { + return m.buffers +} + +func (m *mockSaver) SaveBlobAsync(_ context.Context, _ restic.BlobType, buf *restic.BlobBuffer, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, sizeInRepo int, err error)) { // Fake async operation go func() { m.mutex.Lock() - m.saved[string(buf)]++ + m.saved[string(buf.Data)]++ m.mutex.Unlock() - cb(restic.Hash(buf), false, len(buf), nil) + cb(restic.Hash(buf.Data), false, len(buf.Data), nil) }() } diff --git a/internal/repository/repository.go b/internal/repository/repository.go index 7d59d2b67..3e29749c6 100644 --- a/internal/repository/repository.go +++ b/internal/repository/repository.go @@ -54,6 +54,8 @@ type Repository struct { zeroChunkOnce sync.Once zeroChunkID restic.ID + + blobBuffers *restic.BlobBufferPool } // internalRepository allows using SaveUnpacked and RemoveUnpacked with all FileTypes @@ -381,10 +383,12 @@ func (r *Repository) getZstdDecoder() *zstd.Decoder { // is small enough, it will be packed together with other small blobs. The // caller must ensure that the id matches the data. Returned is the size data // occupies in the repo (compressed or not, including the encryption overhead). -func (r *Repository) saveAndEncrypt(ctx context.Context, t restic.BlobType, data []byte, id restic.ID) (size int, err error) { - debug.Log("save id %v (%v, %d bytes)", id, t, len(data)) +// plaintext is consumed and released before this function returns. +func (r *Repository) saveAndEncrypt(ctx context.Context, t restic.BlobType, plaintext *restic.BlobBuffer, id restic.ID) (size int, err error) { + debug.Log("save id %v (%v, %d bytes)", id, t, len(plaintext.Data)) uncompressedLength := 0 + scratch := plaintext if r.cfg.Version > 1 { // we have a repo v2, so compression is available. if the user opts to // not compress, we won't compress any data, but everything else is @@ -392,21 +396,24 @@ func (r *Repository) saveAndEncrypt(ctx context.Context, t restic.BlobType, data // uncompressedLength != 0 is used to indicate compressed data. Thus, a zero-sized blob // cannot be compressed. This special case is only relevant for tests, normal operation does not // generate zero-sized blobs. - if len(data) > 0 && (r.opts.Compression != CompressionOff || t != restic.DataBlob) { - uncompressedLength = len(data) - data = r.getZstdEncoder().EncodeAll(data, nil) + if len(plaintext.Data) > 0 && (r.opts.Compression != CompressionOff || t != restic.DataBlob) { + uncompressedLength = len(plaintext.Data) + scratch = r.blobBuffers.Get() + scratch.Data = r.getZstdEncoder().EncodeAll(plaintext.Data, scratch.Data[:0]) + plaintext.Release() } } + cipherBuf := r.blobBuffers.Get() + defer cipherBuf.Release() // last buffer in this method such that we can use defer nonce := crypto.NewRandomNonce() - - ciphertext := make([]byte, 0, crypto.CiphertextLength(len(data))) - ciphertext = append(ciphertext, nonce...) + cipherBuf.Data = append(cipherBuf.Data, nonce...) // encrypt blob - ciphertext = r.key.Seal(ciphertext, nonce, data, nil) + cipherBuf.Data = r.key.Seal(cipherBuf.Data, nonce, scratch.Data, nil) + scratch.Release() - if err := r.verifyCiphertext(ciphertext, uncompressedLength, id); err != nil { + if err := r.verifyCiphertext(cipherBuf.Data, uncompressedLength, id); err != nil { //nolint:revive,staticcheck // ignore linter warnings about error message spelling return 0, fmt.Errorf("Detected data corruption while saving blob %v: %w\nCorrupted blobs are either caused by hardware issues or software bugs. Please open an issue at https://github.com/restic/restic/issues/new/choose for further troubleshooting.", id, err) } @@ -423,7 +430,8 @@ func (r *Repository) saveAndEncrypt(ctx context.Context, t restic.BlobType, data panic(fmt.Sprintf("invalid type: %v", t)) } - return pm.SaveBlob(ctx, t, id, ciphertext, uncompressedLength) + size, err = pm.SaveBlob(ctx, t, id, cipherBuf.Data, uncompressedLength) + return size, err } func (r *Repository) verifyCiphertext(buf []byte, uncompressedLength int, id restic.ID) error { @@ -568,9 +576,18 @@ func (r *Repository) removeUnpacked(ctx context.Context, t restic.FileType, id r return r.be.Remove(ctx, backend.Handle{Type: backend.FileType(t), Name: id.String()}) } +func (r *Repository) blobBufferCapacity() int { + // add 1kb to account for overhead from crypto / compression + return chunker.MaxSize + 1024 +} + func (r *Repository) WithBlobUploader(ctx context.Context, fn func(ctx context.Context, uploader restic.BlobSaverWithAsync) error) error { ctx, cancel := context.WithCancel(ctx) defer cancel() + buffers := restic.NewBlobBufferPool(r.blobBufferCapacity()) + r.blobBuffers = buffers + defer func() { r.blobBuffers = nil }() + wg, ctx := errgroup.WithContext(ctx) // pack uploader + wg.Go below + blob saver (CPU bound) wg.SetLimit(2 + runtime.GOMAXPROCS(0)) @@ -621,11 +638,15 @@ type blobSaverRepo struct { repo *Repository } -func (r *blobSaverRepo) SaveBlob(ctx context.Context, t restic.BlobType, buf []byte, id restic.ID, storeDuplicate bool) (newID restic.ID, known bool, size int, err error) { - return r.repo.saveBlob(ctx, t, buf, id, storeDuplicate) +func (r *blobSaverRepo) BlobBufferPool() *restic.BlobBufferPool { + return r.repo.blobBuffers } -func (r *blobSaverRepo) SaveBlobAsync(ctx context.Context, t restic.BlobType, buf []byte, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, size int, err error)) { +func (r *blobSaverRepo) SaveBlob(ctx context.Context, t restic.BlobType, buf []byte, id restic.ID, storeDuplicate bool) (newID restic.ID, known bool, size int, err error) { + return r.repo.saveBlob(ctx, t, restic.NewBuffer(buf), id, storeDuplicate) +} + +func (r *blobSaverRepo) SaveBlobAsync(ctx context.Context, t restic.BlobType, buf *restic.BlobBuffer, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, size int, err error)) { r.repo.saveBlobAsync(ctx, t, buf, id, storeDuplicate, cb) } @@ -1029,9 +1050,10 @@ func (r *Repository) Close() error { // Also returns if the blob was already known before. // If the blob was not known before, it returns the number of bytes the blob // occupies in the repo (compressed or not, including encryption overhead). -func (r *Repository) saveBlob(ctx context.Context, t restic.BlobType, buf []byte, id restic.ID, storeDuplicate bool) (newID restic.ID, known bool, size int, err error) { +func (r *Repository) saveBlob(ctx context.Context, t restic.BlobType, buf *restic.BlobBuffer, id restic.ID, storeDuplicate bool) (newID restic.ID, known bool, size int, err error) { - if int64(len(buf)) > math.MaxUint32 { + if int64(len(buf.Data)) > math.MaxUint32 { + buf.Release() return restic.ID{}, false, 0, fmt.Errorf("blob is larger than 4GB") } @@ -1040,30 +1062,33 @@ func (r *Repository) saveBlob(ctx context.Context, t restic.BlobType, buf []byte // Special case the hash calculation for all zero chunks. This is especially // useful for sparse files containing large all zero regions. For these we can // process chunks as fast as we can read the from disk. - if len(buf) == chunker.MinSize && restic.ZeroPrefixLen(buf) == chunker.MinSize { + if len(buf.Data) == chunker.MinSize && restic.ZeroPrefixLen(buf.Data) == chunker.MinSize { newID = r.zeroChunk() } else { - newID = restic.Hash(buf) + newID = restic.Hash(buf.Data) } } else { newID = id } // first try to add to pending blobs; if not successful, this blob is already known - known = !r.idx.AddPending(restic.BlobHandle{ID: newID, Type: t}, uint(len(buf))) + known = !r.idx.AddPending(restic.BlobHandle{ID: newID, Type: t}, uint(len(buf.Data))) // only save when needed or explicitly told if !known || storeDuplicate { size, err = r.saveAndEncrypt(ctx, t, buf, newID) + } else { + buf.Release() } return newID, known, size, err } -func (r *Repository) saveBlobAsync(ctx context.Context, t restic.BlobType, buf []byte, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, size int, err error)) { +func (r *Repository) saveBlobAsync(ctx context.Context, t restic.BlobType, buf *restic.BlobBuffer, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, size int, err error)) { r.mainWg.Go(func() error { if ctx.Err() != nil { // fail fast if the context is cancelled + buf.Release() cb(restic.ID{}, false, 0, ctx.Err()) return ctx.Err() } diff --git a/internal/repository/repository_test.go b/internal/repository/repository_test.go index e66c18102..5d3895d32 100644 --- a/internal/repository/repository_test.go +++ b/internal/repository/repository_test.go @@ -565,7 +565,7 @@ func TestSaveBlobAsync(t *testing.T) { for i := range numCalls { // Use unique data for each call testData := fmt.Appendf(nil, "test blob data %d", i) - uploader.SaveBlobAsync(ctx, restic.DataBlob, testData, restic.ID{}, false, + uploader.SaveBlobAsync(ctx, restic.DataBlob, restic.NewBuffer(testData), restic.ID{}, false, func(newID restic.ID, known bool, size int, err error) { defer wg.Done() resultsMutex.Lock() @@ -596,7 +596,7 @@ func TestSaveBlobAsyncErrorHandling(t *testing.T) { err := repo.WithBlobUploader(ctx, func(ctx context.Context, uploader restic.BlobSaverWithAsync) error { cancel() // Callback must be called even if the context is canceled - uploader.SaveBlobAsync(ctx, restic.DataBlob, []byte("test blob data"), restic.ID{}, false, + uploader.SaveBlobAsync(ctx, restic.DataBlob, restic.NewBuffer([]byte("test blob data")), restic.ID{}, false, func(newID restic.ID, known bool, size int, err error) { callbackCalled.Store(true) }) diff --git a/internal/restic/buffer.go b/internal/restic/buffer.go new file mode 100644 index 000000000..6178c9f1c --- /dev/null +++ b/internal/restic/buffer.go @@ -0,0 +1,54 @@ +package restic + +import "sync" + +// BlobBuffer is a reusable buffer. After the buffer has been used, Release should +// be called so the underlying slice is put back into the pool. +type BlobBuffer struct { + Data []byte + pool *BlobBufferPool +} + +// Release puts the buffer back into the pool it came from. For buffers created +// with NewBuffer, Release is a no-op. +func (b *BlobBuffer) Release() { + pool := b.pool + if pool == nil || cap(b.Data) > pool.defaultSize { + return + } + + pool.pool.Put(b) +} + +// BlobBufferPool implements a limited set of reusable buffers. +type BlobBufferPool struct { + pool sync.Pool + defaultSize int +} + +// NewBlobBufferPool initializes a new buffer pool. New buffers are created +// with defaultSize. Buffers that have grown larger are not put back. +func NewBlobBufferPool(defaultSize int) *BlobBufferPool { + b := &BlobBufferPool{ + defaultSize: defaultSize, + } + b.pool = sync.Pool{New: func() any { + return &BlobBuffer{ + Data: make([]byte, defaultSize), + pool: b, + } + }} + return b +} + +// Get returns a buffer from the pool. It is guaranteed that the buffer has zero length. +func (pool *BlobBufferPool) Get() *BlobBuffer { + buf := pool.pool.Get().(*BlobBuffer) + buf.Data = buf.Data[:0] + return buf +} + +// NewBuffer wraps an existing slice. Release is a no-op. +func NewBuffer(data []byte) *BlobBuffer { + return &BlobBuffer{Data: data} +} diff --git a/internal/archiver/buffer_test.go b/internal/restic/buffer_test.go similarity index 68% rename from internal/archiver/buffer_test.go rename to internal/restic/buffer_test.go index 65263c5a2..12682c5ec 100644 --- a/internal/archiver/buffer_test.go +++ b/internal/restic/buffer_test.go @@ -1,24 +1,29 @@ -package archiver +package restic import ( "testing" ) -func TestBufferPoolReuse(t *testing.T) { +func TestBlobBufferPoolReuse(t *testing.T) { success := false // retries to avoid flakiness. The test can fail depending on the GC. - for range 100 { + for i := 0; i < 100; i++ { // Test that buffers are actually reused from the pool - pool := newBufferPool(1024) + pool := NewBlobBufferPool(1024) // Get a buffer and modify it buf1 := pool.Get() - buf1.Data[0] = 0xFF + if cap(buf1.Data) < 1024 { + t.Fatalf("buffer capacity %d, want at least 1024", cap(buf1.Data)) + } + buf1.Data = append(buf1.Data, 0xFF) originalAddr := &buf1.Data[0] buf1.Release() // Get another buffer and check if it's the same underlying slice buf2 := pool.Get() + // extend buffer to allow getting the address of the first byte + buf2.Data = append(buf2.Data, 0) if &buf2.Data[0] == originalAddr { success = true break @@ -30,12 +35,12 @@ func TestBufferPoolReuse(t *testing.T) { } } -func TestBufferPoolLargeBuffers(t *testing.T) { +func TestBlobBufferPoolLargeBuffers(t *testing.T) { success := false // retries to avoid flakiness. The test can fail depending on the GC. - for range 100 { + for i := 0; i < 100; i++ { // Test that buffers larger than defaultSize are not returned to pool - pool := newBufferPool(1024) + pool := NewBlobBufferPool(1024) buf := pool.Get() // Grow the buffer beyond default size @@ -50,6 +55,7 @@ func TestBufferPoolLargeBuffers(t *testing.T) { success = true break } + newBuf.Release() } if !success { diff --git a/internal/restic/repository.go b/internal/restic/repository.go index 07f6c8a50..527ef0ff4 100644 --- a/internal/restic/repository.go +++ b/internal/restic/repository.go @@ -131,9 +131,10 @@ type BlobSaver interface { } type BlobSaverAsync interface { + BlobBufferPool() *BlobBufferPool // SaveBlobAsync saves a blob to the repository. ctx must be derived from the context created by WithBlobUploader. - // The callback is called asynchronously from a different goroutine. - SaveBlobAsync(ctx context.Context, tpe BlobType, buf []byte, id ID, storeDuplicate bool, cb func(newID ID, known bool, sizeInRepo int, err error)) + // The callback is called asynchronously from a different goroutine. The buffer will always be released before the callback is called. + SaveBlobAsync(ctx context.Context, tpe BlobType, buf *BlobBuffer, id ID, storeDuplicate bool, cb func(newID ID, known bool, sizeInRepo int, err error)) } // Loader loads a blob from a repository.