From a89971ff66eb8b072587b8bddff711a04a3fa1ec Mon Sep 17 00:00:00 2001 From: MapleWhiteZZZ <421700801@qq.com> Date: Thu, 3 Dec 2026 06:10:27 +0800 Subject: [PATCH] filer: delete the chunks a failed copy wrote (#13316) * filer: delete the chunks a failed copy wrote A copy through the filer (POST dst?cp.from=src) writes the destination's chunks first and its entry last. When it ended before the entry was written (the client gave up, a chunk failed to copy, the entry write failed), the chunks already on the volume servers stayed there, with no entry to reference them and nothing to delete them. The fan-out now waits for the copies it started, starts no further one after a failure or once the request has ended, and deletes what the completed ones wrote. A chunk copy that fails deletes the file id it was assigned, as a failed write can still have stored the needle. A failed entry write deletes only the chunks the destination does not hold, since CreateEntry can fail after storing the entry. #13217 did the same for the S3 copy paths. * filer: keep the copied chunks when the entry write fails CreateEntry can fail after it stored the entry: the entry stays when only its parent folders could not be created. Reading the destination afterwards does not settle whether the chunks are live, since an entry that was stored may have been renamed by then, and deleting on a miss would take its data. So a failed entry write keeps the chunks, as it did before. Only the failures that come before the entry write delete what the copy wrote. * filer: fail a copy whose request ended after its last chunk A request cancelled once every chunk copy had returned still handed the chunks on, to an entry write that the cancelled context then fails, and that write keeps them. The end of the request now fails the fan-out whether or not a copy was left to start, so the chunks are deleted there. --------- Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com> --- weed/server/filer_server_handlers_copy.go | 151 ++++++++++++------ ...filer_server_handlers_copy_cleanup_test.go | 126 +++++++++++++++ 2 files changed, 232 insertions(+), 45 deletions(-) create mode 100644 weed/server/filer_server_handlers_copy_cleanup_test.go diff --git a/weed/server/filer_server_handlers_copy.go b/weed/server/filer_server_handlers_copy.go index bdcd4e54f8..7281d0f717 100644 --- a/weed/server/filer_server_handlers_copy.go +++ b/weed/server/filer_server_handlers_copy.go @@ -196,6 +196,10 @@ func (fs *FilerServer) copy(ctx context.Context, w http.ResponseWriter, r *http. // Pass o_excl = !overwrite so the default copy refuses to replace an // existing destination, while overwrite=true updates the pre-created target. if createErr := fs.filer.CreateEntry(ctx, newEntry, nil, !overwrite, false, nil, false, fs.filer.MaxFilenameLength); createErr != nil { + // The copied chunks are kept. CreateEntry can fail after it stored the + // entry (the entry stays when only its parent folders could not be + // created), and a lookup of the destination now cannot tell an entry + // that was never stored from one that was stored and renamed since. err = fmt.Errorf("failed to create copied entry from '%s' to '%s': %w", src, dst, createErr) writeJsonError(w, r, http.StatusInternalServerError, err) return @@ -517,16 +521,6 @@ func (fs *FilerServer) copyChunks(ctx context.Context, srcChunks []*filer_pb.Fil return nil, fmt.Errorf("failed to lookup volume locations: %w", err) } - // Parallel chunk copying with concurrency control using errgroup - const maxConcurrentChunks = 8 // Match SeaweedFS standard for parallel operations - - // Pre-allocate result slice to maintain order - newChunks := make([]*filer_pb.FileChunk, len(srcChunks)) - - // Use errgroup for cleaner concurrency management - g, gCtx := errgroup.WithContext(ctx) - g.SetLimit(maxConcurrentChunks) // Limit concurrent goroutines - // Validate that all chunk locations are available before starting any concurrent work for _, chunk := range srcChunks { volumeId := chunk.Fid.VolumeId @@ -536,50 +530,104 @@ func (fs *FilerServer) copyChunks(ctx context.Context, srcChunks []*filer_pb.Fil } } - glog.V(2).InfofCtx(ctx, "FilerServer.copyChunks: starting parallel copy of %d chunks with max concurrency %d", len(srcChunks), maxConcurrentChunks) + glog.V(2).InfofCtx(ctx, "FilerServer.copyChunks: starting parallel copy of %d chunks with max concurrency %d", len(srcChunks), maxConcurrentChunkCopies) - // Launch goroutines for each chunk - for i, srcChunk := range srcChunks { - // Capture loop variables for goroutine closure - chunkIndex := i - chunk := srcChunk - chunkLocations := volumeLocationsMap[srcChunk.Fid.VolumeId] + newChunks, err := fs.copyChunksInParallel(ctx, len(srcChunks), func(ctx context.Context, chunkIndex int) (*filer_pb.FileChunk, error) { + chunk := srcChunks[chunkIndex] + glog.V(3).InfofCtx(ctx, "FilerServer.copyChunks: copying chunk %d/%d, size=%d", chunkIndex+1, len(srcChunks), chunk.Size) - g.Go(func() error { - glog.V(3).InfofCtx(gCtx, "FilerServer.copyChunks: copying chunk %d/%d, size=%d", chunkIndex+1, len(srcChunks), chunk.Size) - - // Use streaming copy to avoid loading entire chunk into memory - newChunk, err := fs.streamCopyChunk(gCtx, chunk, so, client, chunkLocations) - if err != nil { - return fmt.Errorf("failed to copy chunk %d (%s): %w", chunkIndex+1, chunk.GetFileIdString(), err) - } - - // Store result at correct index to maintain order - newChunks[chunkIndex] = newChunk - - glog.V(4).InfofCtx(gCtx, "FilerServer.copyChunks: successfully copied chunk %d/%d", chunkIndex+1, len(srcChunks)) - return nil - }) - } - - // Wait for all chunks to complete and return first error (if any) - if err := g.Wait(); err != nil { - return nil, err - } - - // Verify all chunks were copied (shouldn't happen if no errors, but safety check) - for i, chunk := range newChunks { - if chunk == nil { - return nil, fmt.Errorf("chunk %d was not copied (internal error)", i) + // Use streaming copy to avoid loading entire chunk into memory + newChunk, err := fs.streamCopyChunk(ctx, chunk, so, client, volumeLocationsMap[chunk.Fid.VolumeId]) + if err != nil { + return nil, fmt.Errorf("failed to copy chunk %d (%s): %w", chunkIndex+1, chunk.GetFileIdString(), err) } + + glog.V(4).InfofCtx(ctx, "FilerServer.copyChunks: successfully copied chunk %d/%d", chunkIndex+1, len(srcChunks)) + return newChunk, nil + }) + if err != nil { + return nil, err } glog.V(2).InfofCtx(ctx, "FilerServer.copyChunks: successfully completed parallel copy of %d chunks", len(srcChunks)) return newChunks, nil } +// maxConcurrentChunkCopies bounds the chunk copies one request runs at once. +const maxConcurrentChunkCopies = 8 + +// copyChunksInParallel runs copyOne for chunk indexes 0..n-1, at most +// maxConcurrentChunkCopies at a time, and returns the copied chunks in index +// order. +// +// The first failure cancels the copies still running and starts no further +// one, and so does the end of the request, which fails the copy even when it +// comes after the last chunk. Once the copies have all returned, the chunks +// they wrote are deleted, since the failed request leaves no entry that holds +// them. +func (fs *FilerServer) copyChunksInParallel(ctx context.Context, n int, copyOne func(ctx context.Context, chunkIndex int) (*filer_pb.FileChunk, error)) ([]*filer_pb.FileChunk, error) { + // Pre-allocate result slice to maintain order + newChunks := make([]*filer_pb.FileChunk, n) + + g, gCtx := errgroup.WithContext(ctx) + g.SetLimit(maxConcurrentChunkCopies) + + started := 0 + for ; started < n && gCtx.Err() == nil; started++ { + chunkIndex := started + g.Go(func() error { + // g.Go may have waited for a free slot until after the failure + if gCtx.Err() != nil { + return context.Cause(gCtx) + } + newChunk, err := copyOne(gCtx, chunkIndex) + if err != nil { + return err + } + if newChunk == nil { + return fmt.Errorf("chunk %d was not copied (internal error)", chunkIndex) + } + // Store result at correct index to maintain order + newChunks[chunkIndex] = newChunk + return nil + }) + } + + // Wait for every started copy and return the first error (if any) + err := g.Wait() + if err == nil && (started < n || ctx.Err() != nil) { + // The request ended: some copies were never started, or every copy is + // done and no entry will be written for them + err = fmt.Errorf("copied %d of %d chunks: %w", started, n, context.Cause(ctx)) + } + if err != nil { + fs.deleteCopiedChunks(ctx, newChunks) + return nil, err + } + return newChunks, nil +} + +// deleteCopiedChunks removes chunks a copy wrote for an entry that was never +// written. It is best-effort: the deletions are queued like those of any +// replaced chunk, and never change the error the client is answered with. +func (fs *FilerServer) deleteCopiedChunks(ctx context.Context, 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).InfofCtx(ctx, "copy failed, deleting %d chunks it wrote", len(written)) + // A client that gave up is the usual reason a copy fails, and resolving a + // manifest chunk must not fail along with its request. + fs.filer.DeleteUncommittedChunks(context.WithoutCancel(ctx), written) +} + // copyChunksWithManifest handles copying chunks that include manifest chunks -func (fs *FilerServer) copyChunksWithManifest(ctx context.Context, srcChunks []*filer_pb.FileChunk, so *operation.StorageOption, client *http.Client) ([]*filer_pb.FileChunk, error) { +func (fs *FilerServer) copyChunksWithManifest(ctx context.Context, srcChunks []*filer_pb.FileChunk, so *operation.StorageOption, client *http.Client) (_ []*filer_pb.FileChunk, err error) { if len(srcChunks) == 0 { return nil, nil } @@ -590,6 +638,13 @@ func (fs *FilerServer) copyChunksWithManifest(ctx context.Context, srcChunks []* manifestChunks, nonManifestChunks := filer.SeparateManifestChunks(srcChunks) var newChunks []*filer_pb.FileChunk + // A step that fails leaves the chunks of the steps before it with no entry + // to hold them. + defer func() { + if err != nil { + fs.deleteCopiedChunks(ctx, newChunks) + } + }() // First, copy all non-manifest chunks directly if len(nonManifestChunks) > 0 { @@ -627,6 +682,8 @@ func (fs *FilerServer) copyChunksWithManifest(ctx context.Context, srcChunks []* // Create a new manifest chunk that references the copied data chunks newManifestChunk, err := fs.createManifestChunk(ctx, newResolvedChunks, manifestChunk, so, client) if err != nil { + // No manifest lists these yet, so they are deleted on their own. + fs.deleteCopiedChunks(ctx, newResolvedChunks) return nil, fmt.Errorf("failed to create new manifest chunk: %w", err) } @@ -668,6 +725,7 @@ func (fs *FilerServer) createManifestChunk(ctx context.Context, dataChunks []*fi // Upload the manifest data err = fs.uploadData(ctx, reader, urlLocation, string(auth), client) if err != nil { + fs.deleteCopiedChunks(ctx, []*filer_pb.FileChunk{{FileId: fileId}}) return nil, fmt.Errorf("failed to upload manifest data: %w", err) } @@ -798,7 +856,10 @@ func (fs *FilerServer) streamCopyChunk(ctx context.Context, srcChunk *filer_pb.F return newChunk, nil } - // All locations failed + // All locations failed. A write that failed can still have stored the needle: + // a volume server answers 5xx after its local write when a replica fails, and + // a cancelled request loses the answer. Nothing will reference this file id. + fs.deleteCopiedChunks(ctx, []*filer_pb.FileChunk{{FileId: fileId}}) return nil, fmt.Errorf("failed to stream copy chunk from any location: %w", lastErr) } diff --git a/weed/server/filer_server_handlers_copy_cleanup_test.go b/weed/server/filer_server_handlers_copy_cleanup_test.go new file mode 100644 index 0000000000..73b8800d30 --- /dev/null +++ b/weed/server/filer_server_handlers_copy_cleanup_test.go @@ -0,0 +1,126 @@ +package weed_server + +import ( + "context" + "errors" + "fmt" + "sort" + "sync" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" +) + +func copiedChunk(i int) *filer_pb.FileChunk { + return &filer_pb.FileChunk{FileId: fmt.Sprintf("7,%02x637037d6", i+1), Size: 4} +} + +// A copy that fails has no entry to hold the chunks it already wrote, so they +// are deleted: the ones whose copy completed, and no other. +func TestCopyChunksInParallelDeletesWrittenChunksOnFailure(t *testing.T) { + fs := &FilerServer{filer: newRenameTestFiler(t, newRenameTestStore())} + + const n, failing, cutShort = 3 * maxConcurrentChunkCopies, 5, 6 + copyErr := errors.New("source returned status 404") + firstWritten := make(chan struct{}) + var once sync.Once + var mu sync.Mutex + var written []string + + newChunks, err := fs.copyChunksInParallel(context.Background(), n, func(ctx context.Context, i int) (*filer_pb.FileChunk, error) { + switch i { + case failing: + // Fails once another chunk is on the volume servers. + <-firstWritten + return nil, copyErr + case cutShort: + // A transfer the failure cancels stores nothing. + <-ctx.Done() + return nil, ctx.Err() + } + chunk := copiedChunk(i) + mu.Lock() + written = append(written, chunk.FileId) + mu.Unlock() + once.Do(func() { close(firstWritten) }) + return chunk, nil + }) + + if !errors.Is(err, copyErr) { + t.Fatalf("error = %v, want the first copy failure", err) + } + if newChunks != nil { + t.Fatalf("a failed copy returned %d chunks", len(newChunks)) + } + if len(written) == 0 || len(written) > n-2 { + t.Fatalf("%d chunks written, want between 1 and %d", len(written), n-2) + } + sort.Strings(written) + checkDeletions(t, fs.filer, written...) +} + +func TestCopyChunksInParallelKeepsTheChunksOfACompleteCopy(t *testing.T) { + fs := &FilerServer{filer: newRenameTestFiler(t, newRenameTestStore())} + + const n = 3 * maxConcurrentChunkCopies + newChunks, err := fs.copyChunksInParallel(context.Background(), n, func(ctx context.Context, i int) (*filer_pb.FileChunk, error) { + return copiedChunk(i), nil + }) + if err != nil { + t.Fatalf("copy: %v", err) + } + if len(newChunks) != n { + t.Fatalf("%d chunks returned, want %d", len(newChunks), n) + } + for i, chunk := range newChunks { + if want := copiedChunk(i).FileId; chunk.GetFileId() != want { + t.Fatalf("chunk %d is %s, want %s: the order of the source is lost", i, chunk.GetFileId(), want) + } + } + checkDeletions(t, fs.filer) +} + +// The client going away ends the copy too. Every copy in flight may well +// complete: the ones never started must not pass for copied, and a copy whose +// last chunk completes after the client left has no entry coming either. +func TestCopyChunksInParallelDeletesWrittenChunksWhenTheRequestEnds(t *testing.T) { + for _, n := range []int{3 * maxConcurrentChunkCopies, maxConcurrentChunkCopies} { + t.Run(fmt.Sprintf("%d chunks", n), func(t *testing.T) { + fs := &FilerServer{filer: newRenameTestFiler(t, newRenameTestStore())} + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var mu sync.Mutex + var inFlight int + var written []string + + newChunks, err := fs.copyChunksInParallel(ctx, n, func(ctx context.Context, i int) (*filer_pb.FileChunk, error) { + mu.Lock() + inFlight++ + if inFlight == maxConcurrentChunkCopies { + cancel() + } + mu.Unlock() + // The volume server stores the needle all the same. + <-ctx.Done() + chunk := copiedChunk(i) + mu.Lock() + written = append(written, chunk.FileId) + mu.Unlock() + return chunk, nil + }) + + if !errors.Is(err, context.Canceled) { + t.Fatalf("error = %v, want the request's cancellation", err) + } + if newChunks != nil { + t.Fatalf("a copy cut short returned %d chunks", len(newChunks)) + } + if len(written) != maxConcurrentChunkCopies { + t.Fatalf("%d chunks written, want the %d in flight when the request ended", len(written), maxConcurrentChunkCopies) + } + sort.Strings(written) + checkDeletions(t, fs.filer, written...) + }) + } +}