Files
seaweedfs/weed/s3api/s3api_object_handlers_copy_cleanup_test.go
T
30d7f484aa s3api: delete the chunks a failed CopyObject or UploadPartCopy wrote (#13217)
* s3api: delete the chunks a failed CopyObject or UploadPartCopy wrote

A copy writes new needles for the destination before any entry
references them. copyChunks and copyChunksForRange returned on the
first failed chunk without waiting for the copies still running, and
nothing deleted the chunks already written. The running copies went on
to write needles after the request was over; the written ones were never
referenced. The same happened when the copy succeeded and the later
write of the entry failed or a destination precondition refused it, and
in the per-chunk loops of the SSE copy paths.

The concurrent copies now go through copyChunksConcurrently: no further
copy is started after a failure, every started copy is waited for, and
the chunks the others wrote are deleted with deleteOrphanedChunks. The
sequential SSE loops delete what they wrote when they fail part-way. A
chunk a failed copy returned is not kept anywhere, so nothing is left
for volume.fsck.

CopyObject and UploadPartCopy delete the copied chunks when a
precondition or the lock refuses the write, or when the write of the
entry fails and no filer holds an entry at that path that references
them: a failed write can have committed (the answer lost), and chunks
deleted under a stored entry would break the object. An answer the
lookups cannot settle keeps the chunks. Chunks the source entry also
holds (the SSE-KMS same-key rotation hands them back) are never deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: keep a failed copy's chunks when any entry exists at the destination

After a failed write of the destination entry, the copied chunks were
deleted when the first entry the lookup found did not hold them. That
entry can be an older one on one filer while the copy's own entry
committed on another, for example a part written to a filer the routing
failed over to, so the delete could reclaim chunks a stored entry holds.

Delete them only when no filer holds an entry at the path and every filer
answered, as putToFiler does. A copy that fails over an existing object
therefore still leaves its chunks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: keep a copy's chunks when its failed write may still commit

A write of the destination entry that fails without the filer's answer
(a transport failure, a timeout or a cancel) can still be running on the
filer. A lookup that finds no entry then proves nothing: the write can
commit after it, and an entry would reference the chunks the cleanup
deleted.

Keep the copied chunks after such a failure without a lookup; these are
the errors filerErrorToS3Error keeps retryable for the same reason. The
lookup now runs only after the filer answered the write with an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: keep a copy's chunks whenever its write of the entry fails

A failed write of the destination entry can have committed with its
answer lost, or still commit: after a transport failure, or when a
failover replay that another filer refused hides an ambiguous first
attempt. A lookup cannot tell these apart, and chunks deleted under a
stored entry break the object, which is worse than the leak.

CopyObject and UploadPartCopy therefore keep the copied chunks when the
write fails. They still delete them when the lock or a precondition
refuses the write, or the old part cannot be removed, before any entry
write is attempted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: size the copy-owned chunk set without adding slice lengths

CodeQL flags the summed capacity hint as a possible allocation overflow;
the map grows as needed anyway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-01 11:57:00 -08:00

314 lines
12 KiB
Go

package s3api
import (
"fmt"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// chunkCopyFixture is a source object of four 4-byte chunks on the fake volume
// server; the first chunk's needle is missing, so copying it fails.
type chunkCopyFixture struct {
volume *fakeVolumeServer
s3a *S3ApiServer
entry *filer_pb.Entry
srcFids []string
}
func newChunkCopyFixture(t *testing.T) *chunkCopyFixture {
t.Helper()
volume := startFakeVolumeServer(t)
filerImpl := &ambiguousPutFiler{volume: volume, entries: map[string]*filer_pb.Entry{}}
s3a := newPutTestServer(t, startFakeFiler(t, filerImpl))
util_http.InitGlobalHttpClient()
f := &chunkCopyFixture{volume: volume, s3a: s3a, entry: &filer_pb.Entry{
Name: "src",
Attributes: &filer_pb.FuseAttributes{FileSize: 16},
}}
for i := 0; i < 4; i++ {
fid := fmt.Sprintf("3,%016x%08x", 101+2*i, 202+2*i)
f.srcFids = append(f.srcFids, fid)
f.entry.Chunks = append(f.entry.Chunks, &filer_pb.FileChunk{FileId: fid, Offset: int64(4 * i), Size: 4})
if i > 0 {
volume.stored[fid] = []byte("data")
}
}
return f
}
// copiedFids are the needles written to the destination so far.
func (f *chunkCopyFixture) copiedFids() []string {
f.volume.mu.Lock()
defer f.volume.mu.Unlock()
var fids []string
for fid := range f.volume.stored {
if !slices.Contains(f.srcFids, fid) {
fids = append(fids, fid)
}
}
slices.Sort(fids)
return fids
}
func (f *chunkCopyFixture) deletedFids() []string {
fids := f.volume.deleted()
slices.Sort(fids)
return fids
}
// holdCopiesUntilFailure makes chunk 0 fail only after the other three copies
// have reached the destination volume, and keeps those three in flight for a
// further 100ms. It returns once the hooks are armed; done is closed when the
// held copies have been let go.
func (f *chunkCopyFixture) holdCopiesUntilFailure(t *testing.T) (done <-chan struct{}) {
t.Helper()
var arrived atomic.Int32
allArrived := make(chan struct{})
release := make(chan struct{})
f.volume.beforeStore = func(string) {
if arrived.Add(1) == 3 {
close(allArrived)
time.AfterFunc(100*time.Millisecond, func() { close(release) })
}
<-release
}
f.volume.beforeRead = func(fid string) {
if fid != f.srcFids[0] {
return
}
select {
case <-allArrived:
case <-time.After(10 * time.Second):
}
}
return release
}
// A copy that fails on one chunk must not return while the others are still
// being written, and must delete what they wrote: the failed request leaves no
// entry that references those needles.
func TestCopyChunksFailureDeletesCopiedChunksAfterInFlightFinish(t *testing.T) {
f := newChunkCopyFixture(t)
release := f.holdCopiesUntilFailure(t)
dstChunks, err := f.s3a.copyChunks(f.entry, "/buckets/b/dst")
if err == nil || !strings.Contains(err.Error(), "chunk 0") {
t.Fatalf("copyChunks = %v, %v; want the error of chunk 0", dstChunks, err)
}
copied := f.copiedFids()
if len(copied) != 3 {
t.Fatalf("copyChunks returned with %d of 3 chunk copies finished; the others were still in flight", len(copied))
}
if deleted := f.deletedFids(); !slices.Equal(deleted, copied) {
t.Fatalf("deleted chunks = %v, want exactly the copied chunks %v", deleted, copied)
}
<-release
}
// The range copy behind UploadPartCopy cleans up the same way.
func TestCopyChunksForRangeFailureDeletesCopiedChunksAfterInFlightFinish(t *testing.T) {
f := newChunkCopyFixture(t)
release := f.holdCopiesUntilFailure(t)
dstChunks, partMd5, err := f.s3a.copyChunksForRange(f.entry, 0, 15, "/buckets/b/dst")
if err == nil || !strings.Contains(err.Error(), "chunk 0") {
t.Fatalf("copyChunksForRange = %v, %x, %v; want the error of chunk 0", dstChunks, partMd5, err)
}
copied := f.copiedFids()
if len(copied) != 3 {
t.Fatalf("copyChunksForRange returned with %d of 3 chunk copies finished; the others were still in flight", len(copied))
}
if deleted := f.deletedFids(); !slices.Equal(deleted, copied) {
t.Fatalf("deleted chunks = %v, want exactly the copied chunks %v", deleted, copied)
}
<-release
}
// The sequential per-chunk copies of a multipart SSE object delete the chunks
// they already wrote when a later one fails.
func TestCopyMultipartSSEKMSChunksFailureDeletesCopiedChunks(t *testing.T) {
f := newChunkCopyFixture(t)
// the failing chunk is last: reorder so chunks 1..3 are copied first
f.entry.Chunks = append(f.entry.Chunks[1:], f.entry.Chunks[0])
if chunks, _, err := f.s3a.copyMultipartSSEKMSChunks(f.entry, "", nil, false, "/buckets/b/dst", "b"); err == nil {
t.Fatalf("copyMultipartSSEKMSChunks = %v, want an error", chunks)
}
copied := f.copiedFids()
if len(copied) != 3 {
t.Fatalf("copied %d chunks before the failure, want 3", len(copied))
}
if deleted := f.deletedFids(); !slices.Equal(deleted, copied) {
t.Fatalf("deleted chunks = %v, want exactly the copied chunks %v", deleted, copied)
}
}
// Chunks the source entry also holds are not the copy's to delete: the SSE-KMS
// same-key rotation hands the source chunks back as the destination's.
func TestCopyOwnedChunksSkipsSourceChunks(t *testing.T) {
src := []*filer_pb.FileChunk{{FileId: "3,0100000000000001"}, {FileId: "3,0100000000000002"}}
copied := []*filer_pb.FileChunk{{FileId: "3,0200000000000003"}, nil}
manifest := &filer_pb.FileChunk{FileId: "3,0200000000000004", IsChunkManifest: true}
owned := func(dst, entry []*filer_pb.FileChunk) []string {
var fids []string
for _, c := range copyOwnedChunks(src, dst, entry) {
fids = append(fids, c.FileId)
}
return fids
}
if got := owned(src, src); len(got) != 0 {
t.Fatalf("shared source chunks marked for deletion: %v", got)
}
if got := owned(src, []*filer_pb.FileChunk{manifest}); !slices.Equal(got, []string{manifest.FileId}) {
t.Fatalf("a manifest folded over shared chunks: owned = %v, want only %s", got, manifest.FileId)
}
if got := owned(copied, []*filer_pb.FileChunk{manifest}); !slices.Equal(got, []string{"3,0200000000000003", manifest.FileId}) {
t.Fatalf("owned = %v, want the copied chunk and the manifest", got)
}
}
// copyLeakServer is keepAliveCopyServer with a real volume server behind the
// filer, so the handlers' chunk deletes are observable, and a copy step that
// returns the two chunks it "wrote".
func copyLeakServer(t *testing.T, filerImpl *ambiguousPutFiler) (*S3ApiServer, *copyACLFiler, []*filer_pb.FileChunk) {
t.Helper()
oldDelay, oldObject, oldPart := copyKeepAliveDelay, copyObjectData, copyPartData
t.Cleanup(func() { copyKeepAliveDelay, copyObjectData, copyPartData = oldDelay, oldObject, oldPart })
copyKeepAliveDelay = time.Hour
copied := []*filer_pb.FileChunk{
{FileId: "3,0200000000000002", Offset: 0, Size: 2},
{FileId: "3,0200000000000004", Offset: 2, Size: 2},
}
copyObjectData = func(*S3ApiServer, *filer_pb.Entry, *http.Request, string, string, string, string, bool) ([]*filer_pb.FileChunk, map[string][]byte, error) {
return copied, nil, nil
}
copyPartData = func(*S3ApiServer, *filer_pb.Entry, int64, int64, string) ([]*filer_pb.FileChunk, []byte, error) {
return copied, []byte("0123456789abcdef"), nil
}
filer := &copyACLFiler{ambiguousPutFiler: filerImpl}
s3a := newPutTestServer(t, startFakeFiler(t, filer))
s3a.iam = &IdentityAccessManagement{}
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
s3a.bucketConfigCache.Set(keepAliveSrc, &BucketConfig{Name: keepAliveSrc, Ownership: s3_constants.OwnershipObjectWriter})
s3a.bucketConfigCache.Set(keepAliveDst, &BucketConfig{Name: keepAliveDst, Ownership: s3_constants.OwnershipObjectWriter})
filer.entries["/buckets/"+keepAliveSrc+"/"+keepAliveObject] = &filer_pb.Entry{
Name: keepAliveObject,
Attributes: &filer_pb.FuseAttributes{FileMode: defaultFileMode, FileSize: 4, Md5: []byte("0123456789abcdef")},
Chunks: []*filer_pb.FileChunk{{FileId: "3,0100000000000001", Offset: 0, Size: 4}},
}
return s3a, filer, copied
}
func fidsOf(chunks []*filer_pb.FileChunk) []string {
var fids []string
for _, c := range chunks {
fids = append(fids, c.FileId)
}
slices.Sort(fids)
return fids
}
// CopyObject whose destination write fails keeps the chunks it copied and
// answers the write's error. The write can have committed with its answer
// lost, or still commit (a transport failure, or a failover replay refused
// after an ambiguous first attempt), and chunks deleted under a stored entry
// would break the object, which is worse than the leak.
func TestCopyObjectWriteFailureKeepsCopiedChunks(t *testing.T) {
for _, createErr := range []error{
status.Error(codes.InvalidArgument, "refused"),
status.Error(codes.Unavailable, "connection reset"),
} {
volume := startFakeVolumeServer(t)
s3a, _, _ := copyLeakServer(t, &ambiguousPutFiler{
volume: volume, entries: map[string]*filer_pb.Entry{},
createErr: createErr,
})
rr := httptest.NewRecorder()
s3a.CopyObjectHandler(rr, copyObjectRequest("/"+keepAliveSrc+"/"+keepAliveObject))
if rr.Code == http.StatusOK {
t.Fatalf("%v: status = %d, want the write's error", createErr, rr.Code)
}
if got := volume.deleted(); len(got) != 0 {
t.Fatalf("%v: deleted the copied chunks %v after a failed write", createErr, got)
}
}
}
// A write that failed only in its answer has stored the entry: its chunks
// must stay, or the object would read from deleted needles.
func TestCopyObjectAmbiguousWriteKeepsCopiedChunks(t *testing.T) {
volume := startFakeVolumeServer(t)
s3a, filer, _ := copyLeakServer(t, &ambiguousPutFiler{
volume: volume, entries: map[string]*filer_pb.Entry{}, apply: true,
createErr: status.Error(codes.InvalidArgument, "lost response"),
})
rr := httptest.NewRecorder()
s3a.CopyObjectHandler(rr, copyObjectRequest("/"+keepAliveSrc+"/"+keepAliveObject))
if filer.entries["/buckets/"+keepAliveDst+"/"+keepAliveObject] == nil {
t.Fatalf("the fixture did not store the entry; status %d", rr.Code)
}
if got := volume.deleted(); len(got) != 0 {
t.Fatalf("deleted the chunks of a stored entry: %v", got)
}
}
// A destination precondition that fails after the copy ran (another writer
// created the key meanwhile) leaves the copied chunks without an entry, too.
func TestCopyObjectPreconditionFailureDeletesCopiedChunks(t *testing.T) {
volume := startFakeVolumeServer(t)
s3a, filer, copied := copyLeakServer(t, &ambiguousPutFiler{volume: volume, entries: map[string]*filer_pb.Entry{}})
copyData := copyObjectData
copyObjectData = func(s *S3ApiServer, e *filer_pb.Entry, r *http.Request, sb, db, so, do string, rs bool) ([]*filer_pb.FileChunk, map[string][]byte, error) {
filer.mu.Lock()
filer.entries["/buckets/"+keepAliveDst+"/"+keepAliveObject] = &filer_pb.Entry{
Name: keepAliveObject,
Attributes: &filer_pb.FuseAttributes{FileMode: defaultFileMode, FileSize: 1},
}
filer.mu.Unlock()
return copyData(s, e, r, sb, db, so, do, rs)
}
req := copyObjectRequest("/" + keepAliveSrc + "/" + keepAliveObject)
req.Header.Set("If-None-Match", "*")
rr := httptest.NewRecorder()
s3a.CopyObjectHandler(rr, req)
if rr.Code != http.StatusPreconditionFailed {
t.Fatalf("status = %d, want 412; body %q", rr.Code, rr.Body.String())
}
if got := volume.deleted(); !slices.Equal(slices.Sorted(slices.Values(got)), fidsOf(copied)) {
t.Fatalf("deleted chunks = %v, want exactly the copied chunks %v", got, fidsOf(copied))
}
}
// UploadPartCopy whose part write fails keeps the chunks it copied, for the
// same reason.
func TestCopyObjectPartWriteFailureKeepsCopiedChunks(t *testing.T) {
volume := startFakeVolumeServer(t)
s3a, filer, _ := copyLeakServer(t, &ambiguousPutFiler{
volume: volume, entries: map[string]*filer_pb.Entry{},
createErr: status.Error(codes.InvalidArgument, "refused"),
})
rr := httptest.NewRecorder()
s3a.CopyObjectPartHandler(rr, partCopyRequest(s3a, filer, nil))
if rr.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500; body %q", rr.Code, rr.Body.String())
}
if got := volume.deleted(); len(got) != 0 {
t.Fatalf("deleted the copied chunks %v after a failed part write", got)
}
}