filer.copy: continue after a failed file and return a nonzero batch status (#13381)

* filer.copy: finish the batch and report failed copies

* filer.copy: test cleanup after mixed chunk upload outcomes

* filer.copy: check the refused uploads reach the volume in the batch test

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

* filer.copy: drop the trailing newline from entry creation errors

Each copy error is now printed on its own line, so the embedded
newline left a blank line after it.

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-04 10:32:48 -08:00
1 parent 940ecedbfb
commit d6c2662da5
2 files changed
+294 -87

No files matched your search

+53 -73
View File
@@ -12,8 +12,10 @@ import (
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc"
"github.com/seaweedfs/seaweedfs/weed/filer"
@@ -26,10 +28,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util/grace"
)
var (
copyOptions CopyOptions
waitGroup sync.WaitGroup
)
var copyOptions CopyOptions
type CopyOptions struct {
include *string
@@ -155,32 +154,34 @@ func runCopy(cmd *Command, args []string) bool {
*copyOptions.concurrentFiles = concurrentFiles
fileCopyTaskChan := make(chan FileCopyTask, concurrentFiles)
go func() {
defer close(fileCopyTaskChan)
for _, fileOrDir := range fileOrDirs {
if err := genFileCopyTask(fileOrDir, urlPath, fileCopyTaskChan); err != nil {
fmt.Fprintf(os.Stderr, "genFileCopyTask : %v\n", err)
break
}
}
}()
for i := 0; i < concurrentFiles; i++ {
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
var failed atomic.Bool
reportError := func(err error) {
fmt.Fprintf(os.Stderr, "filer.copy: %v\n", err)
failed.Store(true)
}
var workers sync.WaitGroup
for range concurrentFiles {
workers.Go(func() {
worker := FileCopyWorker{
options: &copyOptions,
filerAddress: filerAddress,
signature: util.RandomInt32(),
}
if err := worker.copyFiles(fileCopyTaskChan); err != nil {
fmt.Fprintf(os.Stderr, "copy file error: %v\n", err)
return
for task := range fileCopyTaskChan {
if err := worker.doEachCopy(task); err != nil {
reportError(fmt.Errorf("copy %s: %w", task.sourceLocation, err))
}
}
}()
})
}
for _, fileOrDir := range fileOrDirs {
genFileCopyTask(fileOrDir, urlPath, fileCopyTaskChan, reportError)
}
close(fileCopyTaskChan)
workers.Wait()
if failed.Load() {
SetCommandExitStatus(1)
}
waitGroup.Wait()
return true
}
@@ -200,12 +201,12 @@ func readFilerConfiguration(grpcDialOption grpc.DialOption, filerGrpcAddress pb.
return
}
func genFileCopyTask(fileOrDir string, destPath string, fileCopyTaskChan chan FileCopyTask) error {
func genFileCopyTask(fileOrDir string, destPath string, fileCopyTaskChan chan<- FileCopyTask, reportError func(error)) {
fi, err := os.Stat(fileOrDir)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: read file %s: %v\n", fileOrDir, err)
return nil
reportError(err)
return
}
mode := fi.Mode()
@@ -225,16 +226,15 @@ func genFileCopyTask(fileOrDir string, destPath string, fileCopyTaskChan chan Fi
}
if mode.IsDir() {
files, _ := os.ReadDir(fileOrDir)
files, err := os.ReadDir(fileOrDir)
if err != nil {
reportError(err)
}
for _, subFileOrDir := range files {
cleanedDestDirectory := destPath + fi.Name()
if err = genFileCopyTask(fileOrDir+"/"+subFileOrDir.Name(), cleanedDestDirectory+"/", fileCopyTaskChan); err != nil {
return err
}
genFileCopyTask(filepath.Join(fileOrDir, subFileOrDir.Name()), cleanedDestDirectory+"/", fileCopyTaskChan, reportError)
}
}
return nil
}
type FileCopyWorker struct {
@@ -243,15 +243,6 @@ type FileCopyWorker struct {
signature int32
}
func (worker *FileCopyWorker) copyFiles(fileCopyTaskChan chan FileCopyTask) error {
for task := range fileCopyTaskChan {
if err := worker.doEachCopy(task); err != nil {
return err
}
}
return nil
}
type FileCopyTask struct {
sourceLocation string
destinationUrlPath string
@@ -263,17 +254,6 @@ type FileCopyTask struct {
func (worker *FileCopyWorker) doEachCopy(task FileCopyTask) error {
f, err := os.Open(task.sourceLocation)
if err != nil {
fmt.Printf("Failed to open file %s: %v\n", task.sourceLocation, err)
if _, ok := err.(*os.PathError); ok {
fmt.Printf("skipping %s\n", task.sourceLocation)
return nil
}
return err
}
defer f.Close()
// this is a regular file
if *worker.options.include != "" {
if ok, _ := filepath.Match(*worker.options.include, filepath.Base(task.sourceLocation)); !ok {
@@ -281,6 +261,12 @@ func (worker *FileCopyWorker) doEachCopy(task FileCopyTask) error {
}
}
f, err := os.Open(task.sourceLocation)
if err != nil {
return err
}
defer f.Close()
if shouldCopy, err := worker.checkExistingFileFirst(task, f); err != nil {
return fmt.Errorf("check existing file: %w", err)
} else if !shouldCopy {
@@ -411,7 +397,7 @@ func (worker *FileCopyWorker) uploadFileAsOne(task FileCopyTask, f *os.File) err
}
return nil
}); err != nil {
return fmt.Errorf("upload data %v to http://%s%s%s: %v\n", fileName, worker.filerAddress.ToHttpAddress(), task.destinationUrlPath, fileName, err)
return fmt.Errorf("upload data %v to http://%s%s%s: %w", fileName, worker.filerAddress.ToHttpAddress(), task.destinationUrlPath, fileName, err)
}
return nil
@@ -424,24 +410,19 @@ func (worker *FileCopyWorker) uploadFileInChunks(task FileCopyTask, f *os.File,
chunksChan := make(chan *filer_pb.FileChunk, chunkCount)
concurrentChunks := make(chan struct{}, *worker.options.concurrentChunks)
var wg sync.WaitGroup
var uploadError error
uploads, ctx := errgroup.WithContext(context.Background())
uploads.SetLimit(max(1, *worker.options.concurrentChunks))
fmt.Printf("uploading %s in %d chunks ...\n", fileName, chunkCount)
for i := int64(0); i < int64(chunkCount) && uploadError == nil; i++ {
wg.Add(1)
concurrentChunks <- struct{}{}
go func(i int64) {
defer func() {
wg.Done()
<-concurrentChunks
}()
for i := int64(0); i < int64(chunkCount) && ctx.Err() == nil; i++ {
uploads.Go(func() error {
if err := ctx.Err(); err != nil {
return err
}
uploader, err := operation.NewUploader()
if err != nil {
uploadError = fmt.Errorf("upload data %v: %w\n", fileName, err)
return
return fmt.Errorf("upload data %v: %w", fileName, err)
}
fileId, uploadResult, err, _ := uploader.UploadWithRetry(
@@ -466,19 +447,18 @@ func (worker *FileCopyWorker) uploadFileInChunks(task FileCopyTask, f *os.File,
)
if err != nil {
uploadError = fmt.Errorf("upload data %v: %w\n", fileName, err)
return
return fmt.Errorf("upload data %v: %w", fileName, err)
}
if uploadResult.Error != "" {
uploadError = fmt.Errorf("upload %v result: %v\n", fileName, uploadResult.Error)
return
return fmt.Errorf("upload %v result: %v", fileName, uploadResult.Error)
}
chunksChan <- uploadResult.ToPbFileChunk(fileId, i*chunkSize, time.Now().UnixNano())
fmt.Printf("uploaded %s-%d [%d,%d)\n", fileName, i+1, i*chunkSize, i*chunkSize+int64(uploadResult.Size))
}(i)
return nil
})
}
wg.Wait()
uploadError := uploads.Wait()
close(chunksChan)
var chunks []*filer_pb.FileChunk
@@ -548,7 +528,7 @@ func (worker *FileCopyWorker) uploadFileInChunks(task FileCopyTask, f *os.File,
}
return nil
}); err != nil {
return fmt.Errorf("upload data %v to http://%s%s%s: %v\n", fileName, worker.filerAddress.ToHttpAddress(), task.destinationUrlPath, fileName, err)
return fmt.Errorf("upload data %v to http://%s%s%s: %w", fileName, worker.filerAddress.ToHttpAddress(), task.destinationUrlPath, fileName, err)
}
fmt.Printf("copied %s => http://%s%s%s\n", f.Name(), worker.filerAddress.ToHttpAddress(), task.destinationUrlPath, fileName)
+241 -14
View File
@@ -13,6 +13,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"sync/atomic"
@@ -22,21 +23,31 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
const copyTestVolumeID = "13381"
type copyTestFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
volumeHost string
masters []string
nextKey atomic.Int32
mu sync.Mutex
created *filer_pb.Entry
created []*filer_pb.Entry
}
func (f *copyTestFiler) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) {
return &filer_pb.GetFilerConfigurationResponse{Masters: f.masters}, nil
}
func (f *copyTestFiler) AssignVolume(ctx context.Context, req *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) {
return &filer_pb.AssignVolumeResponse{
FileId: fmt.Sprintf("1,%x637037d6", f.nextKey.Add(1)),
FileId: fmt.Sprintf("%s,%x637037d6", copyTestVolumeID, f.nextKey.Add(1)),
Location: &filer_pb.Location{Url: f.volumeHost, PublicUrl: f.volumeHost},
}, nil
}
@@ -44,10 +55,230 @@ func (f *copyTestFiler) AssignVolume(ctx context.Context, req *filer_pb.AssignVo
func (f *copyTestFiler) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.created = req.Entry
f.created = append(f.created, req.Entry)
return &filer_pb.CreateEntryResponse{}, nil
}
func startCopyTestFiler(t *testing.T, fake *copyTestFiler) pb.ServerAddress {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(srv, fake)
go srv.Serve(lis)
t.Cleanup(srv.Stop)
return pb.NewServerAddress("127.0.0.1", 1, lis.Addr().(*net.TCPAddr).Port)
}
func initCopyTestOptions(t *testing.T) {
t.Helper()
savedOptions, savedStatus := copyOptions, commandExitStatus
t.Cleanup(func() { copyOptions, commandExitStatus = savedOptions, savedStatus })
concurrency, concurrentChunks, maxMB := 1, 2, 1
collection, replication := "", ""
copyOptions.concurrentFiles, copyOptions.maxMB = &concurrency, &maxMB
copyOptions.concurrentChunks = &concurrentChunks
copyOptions.collection, copyOptions.replication = &collection, &replication
commandExitStatus = 0
}
func TestFilerCopyBatchExitStatus(t *testing.T) {
var attemptsMu sync.Mutex
var attempts []string
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, header, err := r.FormFile("file"); err == nil {
attemptsMu.Lock()
attempts = append(attempts, header.Filename)
attemptsMu.Unlock()
}
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{"error": "wrong jwt"})
}))
t.Cleanup(volume.Close)
fake := &copyTestFiler{volumeHost: strings.TrimPrefix(volume.URL, "http://")}
filerAddress := startCopyTestFiler(t, fake)
initCopyTestOptions(t)
dir := t.TempDir()
writeSource := func(name string, size int) string {
t.Helper()
path := filepath.Join(dir, name)
if err := os.WriteFile(path, make([]byte, size), 0600); err != nil {
t.Fatal(err)
}
return path
}
// An empty file only needs a filer entry and can succeed even when the
// volume refuses every upload. One worker makes the task order deterministic.
good := writeSource("good", 0)
for _, tc := range []struct {
name string
sources []string
wantStatus int
attemptPrefix string
}{
{"success", []string{good}, 0, ""},
{"missing source", []string{filepath.Join(dir, "missing"), good}, 1, ""},
{"upload refused", []string{writeSource("small", 1), good}, 1, "small"},
{"chunk uploads refused", []string{writeSource("large", 1024*1024+1), good}, 1, "large-"},
} {
t.Run(tc.name, func(t *testing.T) {
fake.mu.Lock()
fake.created = nil
fake.mu.Unlock()
attemptsMu.Lock()
attempts = nil
attemptsMu.Unlock()
commandExitStatus = 0
if !runCopy(cmdFilerCopy, append(tc.sources, "http://"+string(filerAddress)+"/dest/")) {
t.Fatal("valid copy invocation failed argument validation")
}
if got := CommandExitStatus(); got != tc.wantStatus {
t.Errorf("exit status = %d, want %d", got, tc.wantStatus)
}
attemptsMu.Lock()
reached := slices.ContainsFunc(attempts, func(name string) bool { return strings.HasPrefix(name, tc.attemptPrefix) })
if tc.attemptPrefix == "" && len(attempts) > 0 || tc.attemptPrefix != "" && !reached {
t.Errorf("volume upload attempts = %v, want %q", attempts, tc.attemptPrefix)
}
attemptsMu.Unlock()
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.created) != 1 || fake.created[0].GetName() != "good" {
t.Errorf("created entries = %v, want only good", fake.created)
}
})
}
}
type copyTestMaster struct {
master_pb.UnimplementedSeaweedServer
location *master_pb.Location
}
func (m *copyTestMaster) LookupVolume(context.Context, *master_pb.LookupVolumeRequest) (*master_pb.LookupVolumeResponse, error) {
return &master_pb.LookupVolumeResponse{VolumeIdLocations: []*master_pb.LookupVolumeResponse_VolumeIdLocation{{
VolumeOrFileId: copyTestVolumeID, Locations: []*master_pb.Location{m.location},
}}}, nil
}
type copyTestVolume struct {
volume_server_pb.UnimplementedVolumeServerServer
mu sync.Mutex
uploaded []string
deleted []string
}
func (v *copyTestVolume) BatchDelete(_ context.Context, req *volume_server_pb.BatchDeleteRequest) (*volume_server_pb.BatchDeleteResponse, error) {
v.mu.Lock()
defer v.mu.Unlock()
v.deleted = append(v.deleted, req.FileIds...)
resp := &volume_server_pb.BatchDeleteResponse{}
for _, id := range req.FileIds {
resp.Results = append(resp.Results, &volume_server_pb.DeleteResult{FileId: id, Status: http.StatusAccepted})
}
return resp, nil
}
func TestFilerCopyCleansUpInflightChunks(t *testing.T) {
initCopyTestOptions(t)
// Three chunks share two slots. Chunk 1 frees a slot for chunk 3.
// Chunk 2 holds its response until chunk 3 has sent a terminal rejection.
slowStarted, rejected := make(chan struct{}), make(chan struct{})
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
volume := &copyTestVolume{}
httpVolume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
file, header, err := r.FormFile("file")
if err != nil {
t.Error(err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
switch header.Filename {
case "large-1":
case "large-2":
close(slowStarted)
select {
case <-rejected:
case <-ctx.Done():
t.Error("chunk 3 never rejected its upload")
return
}
case "large-3":
select {
case <-slowStarted:
case <-ctx.Done():
t.Error("chunk 2 never started")
return
}
w.WriteHeader(http.StatusConflict)
fmt.Fprint(w, `{"error":"chunk refused"}`)
if err := http.NewResponseController(w).Flush(); err != nil {
t.Error(err)
}
close(rejected)
return
default:
t.Errorf("unexpected upload %q", header.Filename)
return
}
volume.mu.Lock()
volume.uploaded = append(volume.uploaded, strings.TrimPrefix(r.URL.Path, "/"))
volume.mu.Unlock()
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]any{"name": header.Filename, "size": header.Size})
}))
t.Cleanup(httpVolume.Close)
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := lis.Addr().(*net.TCPAddr).Port
volumeHost := strings.TrimPrefix(httpVolume.URL, "http://")
addr := pb.NewServerAddressWithGrpcPort(volumeHost, port)
fake := &copyTestFiler{volumeHost: volumeHost, masters: []string{string(addr)}}
srv := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(srv, fake)
master_pb.RegisterSeaweedServer(srv, &copyTestMaster{location: &master_pb.Location{Url: volumeHost, GrpcPort: uint32(port)}})
volume_server_pb.RegisterVolumeServerServer(srv, volume)
go srv.Serve(lis)
t.Cleanup(srv.Stop)
t.Cleanup(func() { operation.InvalidateVolumeIdLocationCache(copyTestVolumeID) })
dir := t.TempDir()
large, good := filepath.Join(dir, "large"), filepath.Join(dir, "good")
if err := os.WriteFile(large, make([]byte, 2*1024*1024+1), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(good, nil, 0600); err != nil {
t.Fatal(err)
}
runCopy(cmdFilerCopy, []string{large, good, "http://" + string(addr) + "/dest/"})
if got := CommandExitStatus(); got != 1 {
t.Errorf("exit status = %d, want 1", got)
}
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.created) != 1 || fake.created[0].GetName() != "good" {
t.Errorf("created entries = %v, want only good", fake.created)
}
volume.mu.Lock()
defer volume.mu.Unlock()
if len(volume.uploaded) != 2 {
t.Fatalf("successful uploads = %v, want two", volume.uploaded)
}
slices.Sort(volume.uploaded)
slices.Sort(volume.deleted)
if !slices.Equal(volume.deleted, volume.uploaded) {
t.Errorf("deleted file IDs = %v, want %v", volume.deleted, volume.uploaded)
}
}
func TestUploadFileInChunksStoresChunksInOffsetOrder(t *testing.T) {
// The first chunk finishes last, and the server echoes Content-MD5 back
// the way a volume server does.
@@ -68,14 +299,7 @@ func TestUploadFileInChunksStoresChunksInOffsetOrder(t *testing.T) {
defer volume.Close()
fake := &copyTestFiler{volumeHost: strings.TrimPrefix(volume.URL, "http://")}
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(srv, fake)
go srv.Serve(lis)
defer srv.Stop()
filerAddress := startCopyTestFiler(t, fake)
const chunkSize, chunkCount = 64 * 1024, 3
data := make([]byte, chunkSize*chunkCount)
@@ -100,7 +324,7 @@ func TestUploadFileInChunksStoresChunksInOffsetOrder(t *testing.T) {
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
volumeServerAccess: &access,
},
filerAddress: pb.ServerAddress(fmt.Sprintf("127.0.0.1:1.%d", lis.Addr().(*net.TCPAddr).Port)),
filerAddress: filerAddress,
}
task := FileCopyTask{destinationUrlPath: "/dir/", fileSize: int64(len(data)), fileMode: 0o644}
if err := worker.uploadFileInChunks(task, f, chunkCount, chunkSize); err != nil {
@@ -108,8 +332,11 @@ func TestUploadFileInChunksStoresChunksInOffsetOrder(t *testing.T) {
}
fake.mu.Lock()
chunks := fake.created.GetChunks()
fake.mu.Unlock()
defer fake.mu.Unlock()
if len(fake.created) != 1 {
t.Fatalf("created %d entries, want one", len(fake.created))
}
chunks := fake.created[0].GetChunks()
if len(chunks) != chunkCount {
t.Fatalf("stored %d chunks, want %d", len(chunks), chunkCount)
}