diff --git a/weed/s3api/s3api_object_handlers_copy.go b/weed/s3api/s3api_object_handlers_copy.go index 504ef4dd49..224c1ff2e3 100644 --- a/weed/s3api/s3api_object_handlers_copy.go +++ b/weed/s3api/s3api_object_handlers_copy.go @@ -581,6 +581,7 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request } // Determine whether we can reuse the source MD5 (direct copy without encryption changes). + var copiedChunks []*filer_pb.FileChunk canReuseSourceMd5 := false var sourceMd5 []byte if entry.Attributes != nil && len(entry.Attributes.Md5) > 0 { @@ -656,6 +657,8 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request // re-fold a large copied chunk list, mirroring the PutObject path dstEntry.Chunks = s3a.manifestizeChunks(fmt.Sprintf("%s/%s", s3a.bucketDir(dstBucket), dstObject), dstBucket, 0, dstChunks) + // What this copy wrote, to delete if no entry ends up holding it. + copiedChunks = copyOwnedChunks(entry.GetChunks(), dstChunks, dstEntry.Chunks) // Apply destination-specific metadata (e.g., SSE-C IV and headers) if dstMetadata != nil { @@ -674,12 +677,14 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request var etag string applyPutObjectACL(r, dstEntry) + finalizeStarted := false finalizeCode := s3a.withObjectWriteLock(dstBucket, dstObject, func() s3err.ErrorCode { if errCode := s3a.recheckTagConditionedPolicyWithLookup(dstPolicyReq, dstBucket, dstObject, "", string(s3_constants.ACTION_WRITE), "CopyObjectHandler"); errCode != s3err.ErrNone { return errCode } return s3a.checkConditionalHeaders(r, dstBucket, dstObject) }, func() s3err.ErrorCode { + finalizeStarted = true var finalizeErr error dstVersionId, etag, finalizeErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, dstEntry) if finalizeErr != nil { @@ -688,6 +693,12 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request return s3err.ErrNone }) if finalizeCode != s3err.ErrNone { + // The lock or a precondition refused the write before any entry was + // attempted, so nothing holds the copied chunks. A failed write keeps + // them: it can have committed with its answer lost, or still commit. + if !finalizeStarted { + s3a.deleteCopiedChunks(copiedChunks) + } keepAlive.writeError(finalizeCode) return } @@ -1401,6 +1412,8 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req upload := s3a.uploadFiler(dstBucket, dstObject) if exists, _ := upload.exists(uploadDir, partName, false); exists { if err := upload.rm(r.Context(), uploadDir, partName, false, false); err != nil { + // the part entry is untouched, so nothing holds the chunks just copied + s3a.deleteCopiedChunks(dstEntry.Chunks) keepAlive.writeError(s3err.ErrInternalError) return } @@ -1626,32 +1639,10 @@ func processMetadataBytes(reqHeader http.Header, existing map[string][]byte, rep // copyChunks replicates chunks from source entry to destination entry func (s3a *S3ApiServer) copyChunks(entry *filer_pb.Entry, dstPath string) ([]*filer_pb.FileChunk, error) { - dstChunks := make([]*filer_pb.FileChunk, len(entry.GetChunks())) - const defaultChunkCopyConcurrency = 4 - executor := util.NewLimitedConcurrentExecutor(defaultChunkCopyConcurrency) // Limit to configurable concurrent operations - errChan := make(chan error, len(entry.GetChunks())) - - for i, chunk := range entry.GetChunks() { - chunkIndex := i - executor.Execute(func() { - dstChunk, err := s3a.copySingleChunk(chunk, dstPath) - if err != nil { - errChan <- fmt.Errorf("chunk %d: %w", chunkIndex, err) - return - } - dstChunks[chunkIndex] = dstChunk - errChan <- nil - }) - } - - // Wait for all operations to complete and check for errors - for i := 0; i < len(entry.GetChunks()); i++ { - if err := <-errChan; err != nil { - return nil, err - } - } - - return dstChunks, nil + chunks := entry.GetChunks() + return s3a.copyChunksConcurrently(len(chunks), func(i int) (*filer_pb.FileChunk, error) { + return s3a.copySingleChunk(chunks[i], dstPath) + }) } // copySingleChunk copies a single chunk from source to destination, preserving @@ -1897,30 +1888,11 @@ func (s3a *S3ApiServer) copyChunksForRange(entry *filer_pb.Entry, startOffset, e } // Copy the relevant chunks using a specialized method for range copies - dstChunks := make([]*filer_pb.FileChunk, len(relevantChunks)) - const defaultChunkCopyConcurrency = 4 - executor := util.NewLimitedConcurrentExecutor(defaultChunkCopyConcurrency) - errChan := make(chan error, len(relevantChunks)) - - for i, chunk := range relevantChunks { - chunkIndex := i - originalChunk := originalChunks[i] // Get the corresponding original chunk - executor.Execute(func() { - dstChunk, err := s3a.copySingleChunkForRange(originalChunk, chunk, startOffset, endOffset, dstPath) - if err != nil { - errChan <- fmt.Errorf("chunk %d: %w", chunkIndex, err) - return - } - dstChunks[chunkIndex] = dstChunk - errChan <- nil - }) - } - - // Wait for all operations to complete and check for errors - for i := 0; i < len(relevantChunks); i++ { - if err := <-errChan; err != nil { - return nil, nil, err - } + dstChunks, err := s3a.copyChunksConcurrently(len(relevantChunks), func(i int) (*filer_pb.FileChunk, error) { + return s3a.copySingleChunkForRange(originalChunks[i], relevantChunks[i], startOffset, endOffset, dstPath) + }) + if err != nil { + return nil, nil, err } // Reads resolve overlapping chunks by ModifiedTsNs, and the concurrent @@ -1943,6 +1915,7 @@ func (s3a *S3ApiServer) copyChunksForRange(entry *filer_pb.Entry, startOffset, e if partMd5Ch != nil { if res := <-partMd5Ch; res.err != nil { + s3a.deleteCopiedChunks(dstChunks) return nil, nil, fmt.Errorf("md5 of copied range: %w", res.err) } else { partMd5 = res.sum @@ -1953,6 +1926,7 @@ func (s3a *S3ApiServer) copyChunksForRange(entry *filer_pb.Entry, startOffset, e // copied range when the inherited digest is missing or malformed. sum, err := s3a.copiedRangeMd5(md5Ctx, entry, startOffset, endOffset) if err != nil { + s3a.deleteCopiedChunks(dstChunks) return nil, nil, fmt.Errorf("md5 of copied range: %w", err) } partMd5 = sum @@ -2363,6 +2337,10 @@ func (s3a *S3ApiServer) copyMultipartSSECChunks(entry *filer_pb.Entry, copySourc var dstChunks []*filer_pb.FileChunk var destIV []byte + // A failure part-way leaves the chunks already copied unreferenced. + rollback := s3a.newChunkCopyRollback() + defer rollback.release() + for _, chunk := range entry.GetChunks() { if chunk.GetSseType() != filer_pb.SSEType_SSE_C { // Non-SSE-C chunk, copy directly @@ -2370,6 +2348,7 @@ func (s3a *S3ApiServer) copyMultipartSSECChunks(entry *filer_pb.Entry, copySourc if err != nil { return nil, nil, fmt.Errorf("failed to copy non-SSE-C chunk: %w", err) } + rollback.add(copiedChunk) dstChunks = append(dstChunks, copiedChunk) continue } @@ -2380,6 +2359,7 @@ func (s3a *S3ApiServer) copyMultipartSSECChunks(entry *filer_pb.Entry, copySourc return nil, nil, fmt.Errorf("failed to copy SSE-C chunk %s: %w", chunk.GetFileIdString(), err) } + rollback.add(copiedChunk) dstChunks = append(dstChunks, copiedChunk) // Store the first chunk's IV as the object's IV (for single-part compatibility) @@ -2398,6 +2378,7 @@ func (s3a *S3ApiServer) copyMultipartSSECChunks(entry *filer_pb.Entry, copySourc glog.V(2).Infof("Prepared multipart SSE-C destination metadata: %s", dstPath) } + rollback.commit() return dstChunks, dstMetadata, nil } @@ -2416,6 +2397,10 @@ func (s3a *S3ApiServer) copyMultipartSSEKMSChunks(entry *filer_pb.Entry, destKey var dstChunks []*filer_pb.FileChunk + // A failure part-way leaves the chunks already copied unreferenced. + rollback := s3a.newChunkCopyRollback() + defer rollback.release() + for _, chunk := range entry.GetChunks() { if chunk.GetSseType() != filer_pb.SSEType_SSE_KMS { // Non-SSE-KMS chunk, copy directly @@ -2423,6 +2408,7 @@ func (s3a *S3ApiServer) copyMultipartSSEKMSChunks(entry *filer_pb.Entry, destKey if err != nil { return nil, nil, fmt.Errorf("failed to copy non-SSE-KMS chunk: %w", err) } + rollback.add(copiedChunk) dstChunks = append(dstChunks, copiedChunk) continue } @@ -2434,6 +2420,7 @@ func (s3a *S3ApiServer) copyMultipartSSEKMSChunks(entry *filer_pb.Entry, destKey return nil, nil, fmt.Errorf("failed to copy SSE-KMS chunk %s: %w", chunk.GetFileIdString(), err) } + rollback.add(copiedChunk) dstChunks = append(dstChunks, copiedChunk) } @@ -2466,6 +2453,7 @@ func (s3a *S3ApiServer) copyMultipartSSEKMSChunks(entry *filer_pb.Entry, destKey } } + rollback.commit() return dstChunks, dstMetadata, nil } @@ -2725,6 +2713,11 @@ func (s3a *S3ApiServer) copyMultipartSSECChunk(chunk *filer_pb.FileChunk, copySo func (s3a *S3ApiServer) copyMultipartCrossEncryption(entry *filer_pb.Entry, r *http.Request, state *EncryptionState, dstBucket, dstPath string) ([]*filer_pb.FileChunk, map[string][]byte, error) { var dstChunks []*filer_pb.FileChunk + // A failure part-way, or while building the destination metadata after the + // chunks are copied, leaves them unreferenced. + rollback := s3a.newChunkCopyRollback() + defer rollback.release() + // Parse destination encryption parameters var destSSECKey *SSECustomerKey var destKMSKeyID string @@ -2787,6 +2780,7 @@ func (s3a *S3ApiServer) copyMultipartCrossEncryption(entry *filer_pb.Entry, r *h return nil, nil, fmt.Errorf("failed to copy chunk %s: %w", chunk.GetFileIdString(), err) } + rollback.add(copiedChunk) dstChunks = append(dstChunks, copiedChunk) } @@ -2881,6 +2875,7 @@ func (s3a *S3ApiServer) copyMultipartCrossEncryption(entry *filer_pb.Entry, r *h } // For unencrypted destination, no metadata needed (dstMetadata remains empty) + rollback.commit() return dstChunks, dstMetadata, nil } @@ -3201,11 +3196,6 @@ func (s3a *S3ApiServer) copyChunksWithSSEC(entry *filer_pb.Entry, r *http.Reques // copyChunksWithReencryption handles the slow path: decrypt source and re-encrypt for destination // Returns the destination chunks and the IV used for encryption (if any) func (s3a *S3ApiServer) copyChunksWithReencryption(entry *filer_pb.Entry, copySourceKey *SSECustomerKey, destKey *SSECustomerKey, dstPath string) ([]*filer_pb.FileChunk, []byte, error) { - dstChunks := make([]*filer_pb.FileChunk, len(entry.GetChunks())) - const defaultChunkCopyConcurrency = 4 - executor := util.NewLimitedConcurrentExecutor(defaultChunkCopyConcurrency) // Limit to configurable concurrent operations - errChan := make(chan error, len(entry.GetChunks())) - // Generate a single IV for the destination object (if destination is encrypted) var destIV []byte if destKey != nil { @@ -3215,26 +3205,13 @@ func (s3a *S3ApiServer) copyChunksWithReencryption(entry *filer_pb.Entry, copySo } } - for i, chunk := range entry.GetChunks() { - chunkIndex := i - executor.Execute(func() { - dstChunk, err := s3a.copyChunkWithReencryption(chunk, copySourceKey, destKey, dstPath, entry.Extended, destIV) - if err != nil { - errChan <- fmt.Errorf("chunk %d: %w", chunkIndex, err) - return - } - dstChunks[chunkIndex] = dstChunk - errChan <- nil - }) + chunks := entry.GetChunks() + dstChunks, err := s3a.copyChunksConcurrently(len(chunks), func(i int) (*filer_pb.FileChunk, error) { + return s3a.copyChunkWithReencryption(chunks[i], copySourceKey, destKey, dstPath, entry.Extended, destIV) + }) + if err != nil { + return nil, nil, err } - - // Wait for all operations to complete and check for errors - for i := 0; i < len(entry.GetChunks()); i++ { - if err := <-errChan; err != nil { - return nil, nil, err - } - } - return dstChunks, destIV, nil } @@ -3526,12 +3503,17 @@ func (s3a *S3ApiServer) copyChunksWithSSEKMSReencryption(entry *filer_pb.Entry, glog.V(3).Infof("Extracted source SSE-KMS key: keyID=%s, bucketKey=%t", sourceSSEKey.KeyID, sourceSSEKey.BucketKeyEnabled) } + // A failure part-way leaves the chunks already copied unreferenced. + rollback := s3a.newChunkCopyRollback() + defer rollback.release() + // Process chunks for _, chunk := range entry.GetChunks() { dstChunk, err := s3a.copyChunkWithSSEKMSReencryption(chunk, sourceSSEKey, destKeyID, encryptionContext, bucketKeyEnabled, dstPath, bucket) if err != nil { return nil, nil, fmt.Errorf("copy chunk with SSE-KMS re-encryption: %w", err) } + rollback.add(dstChunk) dstChunks = append(dstChunks, dstChunk) } @@ -3575,6 +3557,7 @@ func (s3a *S3ApiServer) copyChunksWithSSEKMSReencryption(entry *filer_pb.Entry, } } + rollback.commit() return dstChunks, dstMetadata, nil } diff --git a/weed/s3api/s3api_object_handlers_copy_cleanup.go b/weed/s3api/s3api_object_handlers_copy_cleanup.go new file mode 100644 index 0000000000..f5daf76dcb --- /dev/null +++ b/weed/s3api/s3api_object_handlers_copy_cleanup.go @@ -0,0 +1,154 @@ +package s3api + +import ( + "fmt" + "sync/atomic" + + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// chunkCopyConcurrency bounds the chunk copies one request runs at once. +const chunkCopyConcurrency = 4 + +// copyChunksConcurrently runs copyOne for chunk indexes 0..n-1, at most +// chunkCopyConcurrency at a time, and returns the copied chunks in index order. +// +// Every copy that started is waited for before it returns: a copy left running +// would write a needle after the request is over, with nothing to ever reference +// it. When a copy fails, no further copy is started, and the chunks the others +// wrote are deleted, since the failed request leaves no entry that holds them. +func (s3a *S3ApiServer) copyChunksConcurrently(n int, copyOne func(i int) (*filer_pb.FileChunk, error)) ([]*filer_pb.FileChunk, error) { + dstChunks := make([]*filer_pb.FileChunk, n) + executor := util.NewLimitedConcurrentExecutor(chunkCopyConcurrency) + errChan := make(chan error, n) + var failed atomic.Bool + + started := 0 + for i := 0; i < n && !failed.Load(); i++ { + chunkIndex := i + started++ + executor.Execute(func() { + if failed.Load() { + errChan <- nil + return + } + dstChunk, err := copyOne(chunkIndex) + if err != nil { + failed.Store(true) + errChan <- fmt.Errorf("chunk %d: %w", chunkIndex, err) + return + } + dstChunks[chunkIndex] = dstChunk + errChan <- nil + }) + } + + // Collect every started copy, not just up to the first error; the first + // error reported is the one returned. + var firstErr error + for i := 0; i < started; i++ { + if err := <-errChan; err != nil && firstErr == nil { + firstErr = err + } + } + if firstErr != nil { + s3a.deleteCopiedChunks(dstChunks) + return nil, firstErr + } + return dstChunks, nil +} + +// deleteCopiedChunks removes chunks a copy wrote for an entry that was never +// written. It is best-effort: a failed delete is logged and leaves the needles +// for volume.fsck, and never changes the error the client is answered with. +func (s3a *S3ApiServer) deleteCopiedChunks(chunks []*filer_pb.FileChunk) { + written := make([]*filer_pb.FileChunk, 0, len(chunks)) + for _, chunk := range chunks { + if chunk != nil { + written = append(written, chunk) + } + } + if len(written) == 0 { + return + } + glog.V(1).Infof("copy failed, deleting %d chunks it wrote", len(written)) + s3a.deleteOrphanedChunks(written) +} + +// chunkCopyRollback collects the chunks a sequential, multi-step copy writes +// and deletes them if the copy ends without commit. +type chunkCopyRollback struct { + s3a *S3ApiServer + chunks []*filer_pb.FileChunk + committed bool +} + +func (s3a *S3ApiServer) newChunkCopyRollback() *chunkCopyRollback { + return &chunkCopyRollback{s3a: s3a} +} + +func (c *chunkCopyRollback) add(chunk *filer_pb.FileChunk) { + c.chunks = append(c.chunks, chunk) +} + +// commit keeps the chunks: the copy succeeded and the caller owns them now. +func (c *chunkCopyRollback) commit() { c.committed = true } + +// release is deferred by the copy; it deletes the chunks unless commit ran. +func (c *chunkCopyRollback) release() { + if !c.committed { + c.s3a.deleteCopiedChunks(c.chunks) + } +} + +// chunkFidKey identifies a chunk's needle independent of how its file id is +// spelled. +func chunkFidKey(c *filer_pb.FileChunk) string { + fid := c.GetFid() + if fid == nil { + fid, _ = filer_pb.ToFileIdObject(c.GetFileIdString()) + } + if fid == nil { + return c.GetFileIdString() + } + return fmt.Sprintf("%d,%x,%x", fid.VolumeId, fid.FileKey, fid.Cookie) +} + +// copyOwnedChunks returns the chunks a failed copy may delete: the chunks it +// wrote (dstChunks) and the manifest chunks folded over them (entryChunks), +// minus any needle the source entry also holds. A copy that reuses the source's +// chunks (SSE-KMS key rotation onto the same key) writes none of its own for +// them, so those must stay. +func copyOwnedChunks(srcChunks, dstChunks, entryChunks []*filer_pb.FileChunk) []*filer_pb.FileChunk { + shared := make(map[string]struct{}, len(srcChunks)) + for _, chunk := range srcChunks { + shared[chunkFidKey(chunk)] = struct{}{} + } + var owned []*filer_pb.FileChunk + seen := make(map[string]struct{}, len(dstChunks)) + take := func(chunk *filer_pb.FileChunk) { + if chunk == nil { + return + } + key := chunkFidKey(chunk) + if _, isShared := shared[key]; isShared { + return + } + if _, dup := seen[key]; dup { + return + } + seen[key] = struct{}{} + owned = append(owned, chunk) + } + for _, chunk := range dstChunks { + take(chunk) + } + for _, chunk := range entryChunks { + if chunk.GetIsChunkManifest() { + take(chunk) + } + } + return owned +} diff --git a/weed/s3api/s3api_object_handlers_copy_cleanup_test.go b/weed/s3api/s3api_object_handlers_copy_cleanup_test.go new file mode 100644 index 0000000000..af86374d2c --- /dev/null +++ b/weed/s3api/s3api_object_handlers_copy_cleanup_test.go @@ -0,0 +1,313 @@ +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 := ©ACLFiler{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) + } +} diff --git a/weed/s3api/s3api_object_handlers_put_ambiguous_test.go b/weed/s3api/s3api_object_handlers_put_ambiguous_test.go index 2430665c17..47f2d9a415 100644 --- a/weed/s3api/s3api_object_handlers_put_ambiguous_test.go +++ b/weed/s3api/s3api_object_handlers_put_ambiguous_test.go @@ -61,6 +61,11 @@ type fakeVolumeServer struct { // httpDeletedFids records the fids the gateway's own cleanup DELETEs over // HTTP (a failed chunk write), as opposed to BatchDelete's orphan cleanup. httpDeletedFids []string + // beforeRead and beforeStore run when a chunk GET arrives and after a + // chunk POST has read its body (before the chunk is stored), letting a + // test order or hold the legs of a concurrent copy. Set before use. + beforeRead func(fid string) + beforeStore func(fid string) } func (f *fakeVolumeServer) BatchDelete(_ context.Context, req *volume_server_pb.BatchDeleteRequest) (*volume_server_pb.BatchDeleteResponse, error) { @@ -100,6 +105,9 @@ func startFakeVolumeServer(t *testing.T) *fakeVolumeServer { return } if r.Method == http.MethodGet { + if v.beforeRead != nil { + v.beforeRead(fid) + } v.mu.Lock() data, ok := v.stored[fid] v.mu.Unlock() @@ -163,6 +171,9 @@ func startFakeVolumeServer(t *testing.T) *fakeVolumeServer { v.mu.Unlock() return } + if v.beforeStore != nil && r.Method == http.MethodPost { + v.beforeStore(fid) + } v.mu.Lock() v.stored[fid] = data v.mu.Unlock()