Files
seaweedfs/weed/command/filer_copy_test.go
T
d6c2662da5 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>
2026-12-04 10:32:48 -08:00

353 lines
11 KiB
Go

package command
import (
"context"
"crypto/md5"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"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
}
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("%s,%x637037d6", copyTestVolumeID, f.nextKey.Add(1)),
Location: &filer_pb.Location{Url: f.volumeHost, PublicUrl: f.volumeHost},
}, nil
}
func (f *copyTestFiler) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
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.
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
data, _ := io.ReadAll(file)
if strings.HasSuffix(header.Filename, "-1") {
time.Sleep(200 * time.Millisecond)
}
w.Header().Set("Content-MD5", header.Header.Get("Content-MD5"))
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]any{"name": header.Filename, "size": len(data)})
}))
defer volume.Close()
fake := &copyTestFiler{volumeHost: strings.TrimPrefix(volume.URL, "http://")}
filerAddress := startCopyTestFiler(t, fake)
const chunkSize, chunkCount = 64 * 1024, 3
data := make([]byte, chunkSize*chunkCount)
rand.Read(data)
path := filepath.Join(t.TempDir(), "f.bin")
if err := os.WriteFile(path, data, 0o644); err != nil {
t.Fatal(err)
}
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
empty, access, concurrent := "", "url", chunkCount
worker := &FileCopyWorker{
options: &CopyOptions{
replication: &empty,
collection: &empty,
diskType: &empty,
concurrentChunks: &concurrent,
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
volumeServerAccess: &access,
},
filerAddress: filerAddress,
}
task := FileCopyTask{destinationUrlPath: "/dir/", fileSize: int64(len(data)), fileMode: 0o644}
if err := worker.uploadFileInChunks(task, f, chunkCount, chunkSize); err != nil {
t.Fatal(err)
}
fake.mu.Lock()
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)
}
for i, c := range chunks {
if want := int64(i * chunkSize); c.Offset != want {
t.Fatalf("chunk %d is at offset %d, want %d", i, c.Offset, want)
}
sum := md5.Sum(data[i*chunkSize : (i+1)*chunkSize])
if want := base64.StdEncoding.EncodeToString(sum[:]); c.ETag != want {
t.Fatalf("chunk %d ETag = %q, want the md5 of its data %q", i, c.ETag, want)
}
}
}