Files
seaweedfs/weed/s3api/s3api_object_handlers_copy_reassign_test.go
T
85b783cc0d s3api: copy a chunk to another volume when its volume fails the write (#13297)
* s3api: copy a chunk to another volume when its volume fails the write

CopyObject and UploadPartCopy assigned one volume to each copied chunk and
failed the whole copy when that volume failed the write: a streamed copy
sent a single POST, and a buffered copy retried only the same fid.
PutObject asks for a fresh assignment instead (upload_chunked.go), so a
volume that filled up, went away or was overloaded failed a copy that a
PUT would have survived. In production, a CopyObject failed with 500
because the destination volume server broke the connection mid-upload,
and only the client's retry completed it.

Every chunk copy now writes through uploadCopiedChunk: streamed, buffered,
range, and the five SSE re-encryption paths. When a volume fails the write
in a way another volume would not, the copy deletes whatever the failed
write may have stored, asks for another volume and writes the chunk again,
as PutObject does: up to three volumes, and only one more after an
overload. The uploader's errors are judged by
operation.ShouldReassignUpload, and a streamed POST by its status (no
response, a 5xx, or an overload refusal). A streamed retry reads the
source again, and a range copy digests only the bytes of the attempt that
landed. A failed source read is not retried on another volume: a streamed
copy now records the source's read error apart from the POST's.

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

* s3api: delete a failed copy chunk only when its write reached the volume

A streamed copy reads its source inside the write, so a source that could
not be read also came back through uploadCopiedChunk, which then deleted a
fid nothing had been written to. Only a failure of the volume itself
(copyUploadError) is followed by the delete now; the tests check that a
source failure sends none.

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

* s3api: reassign copy writes refused before the append, bound the cleanup

A streamed copy's POST dropped the volume's X-Seaweed-Write-Outcome header,
so a 409 from a volume that turned read-only before the append, or a 401 for
a token that expired in the queue, failed the copy where the uploader's
ShouldReassignUpload tries another volume. The POST now keeps the header and
reassigns on the same marked answers; unmarked 409 and 401 stay final.

The delete of a failed chunk read its answer with no deadline, so a volume
that sent the headers and stalled the body held the copy up for good. Each
delete now runs within copyCleanupTimeout (10s), its answer included, and
still logs the status and up to 4 KiB of the body.

Tests: the fake volume keeps the file it was sent, and each retry case checks
that the second volume stored the copied bytes. An SSE-C chunk copied under a
new key decrypts with the key and IV its chunk names. Marked 409 and 401
answers reassign, unmarked ones do not, and a stalled cleanup delays the copy
by the timeout only.

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

* s3api: renew an expired token for a failed copy chunk's delete

A copy's write token is minted at the assignment, before the source is
read, and lasts 10s by default. A write that failed after that left the
cleanup delete refused with 401 and the needle orphaned. PutObject's
cleanup renews the token from the master on a 401; do the same.

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

* s3api: log the status and body of a cleanup delete whose read failed

A delete whose answer began but whose body read failed, such as one cut
off by copyCleanupTimeout, was logged with the error only. Log its status
and the part of the body that arrived as well.

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-02 12:03:40 -08:00

468 lines
17 KiB
Go

package s3api
import (
"bytes"
"context"
"crypto/md5"
"encoding/base64"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// reassignCopyFiler hands out the destination volumes in turn, one per
// assignment (the last one again once they run out), and serves every source
// volume from src.
type reassignCopyFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
src string
mu sync.Mutex
dsts []*copyVolume
fids []string
}
func (f *reassignCopyFiler) AssignVolume(context.Context, *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
dst := f.dsts[min(len(f.fids), len(f.dsts)-1)]
fid := fmt.Sprintf("%d,01637037d6", 3+len(f.fids))
f.fids = append(f.fids, fid)
return &filer_pb.AssignVolumeResponse{FileId: fid, Location: &filer_pb.Location{Url: dst.host()}}, nil
}
func (f *reassignCopyFiler) LookupVolume(_ context.Context, req *filer_pb.LookupVolumeRequest) (*filer_pb.LookupVolumeResponse, error) {
locations := map[string]*filer_pb.Locations{}
for _, vid := range req.VolumeIds {
locations[vid] = &filer_pb.Locations{Locations: []*filer_pb.Location{{Url: f.src}}}
}
return &filer_pb.LookupVolumeResponse{LocationsMap: locations}, nil
}
func (f *reassignCopyFiler) assigned() []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.fids...)
}
// copyVolume is a destination volume server. It answers every upload with
// status and, when set, the write outcome header outcome, or drops the
// connection when status is 0. It records the fids it was sent and asked to
// delete, and the file the last upload carried. With stallDeletes it answers
// a delete with its headers and never finishes the body.
type copyVolume struct {
status int
outcome string
stallDeletes bool
server *httptest.Server
released chan struct{}
mu sync.Mutex
uploads []string
deletes []string
stored []byte
}
func newCopyVolume(t *testing.T, status int) *copyVolume {
return startCopyVolume(t, &copyVolume{status: status})
}
// startCopyVolume serves v, set up before it starts.
func startCopyVolume(t *testing.T, v *copyVolume) *copyVolume {
v.released = make(chan struct{})
v.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fid := strings.TrimPrefix(r.URL.Path, "/")
if r.Method == http.MethodDelete {
v.mu.Lock()
v.deletes = append(v.deletes, fid)
v.mu.Unlock()
w.WriteHeader(http.StatusAccepted)
if v.stallDeletes {
w.(http.Flusher).Flush()
select {
case <-r.Context().Done():
case <-v.released:
}
}
return
}
body, _ := io.ReadAll(r.Body)
v.mu.Lock()
v.uploads = append(v.uploads, fid)
v.stored = uploadedFile(r.Header.Get("Content-Type"), body)
v.mu.Unlock()
switch v.status {
case 0:
conn, _, err := w.(http.Hijacker).Hijack()
if err == nil {
conn.Close()
}
case http.StatusCreated:
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, `{"size":%d}`, len(body))
default:
if v.outcome != "" {
w.Header().Set(util_http.WriteOutcomeHeader, v.outcome)
}
http.Error(w, "refused", v.status)
}
}))
t.Cleanup(v.server.Close)
// runs first: Close waits for a stalled delete
t.Cleanup(func() { close(v.released) })
return v
}
// uploadedFile returns the file a multipart upload carries, unzipped, or nil.
func uploadedFile(contentType string, body []byte) []byte {
_, params, err := mime.ParseMediaType(contentType)
if err != nil {
return nil
}
part, err := multipart.NewReader(bytes.NewReader(body), params["boundary"]).NextPart()
if err != nil {
return nil
}
data, err := io.ReadAll(part)
if err != nil {
return nil
}
if part.Header.Get("Content-Encoding") == "gzip" {
if data, err = util.DecompressData(data); err != nil {
return nil
}
}
return data
}
func (v *copyVolume) host() string { return strings.TrimPrefix(v.server.URL, "http://") }
func (v *copyVolume) got() (uploads, deletes []string) {
v.mu.Lock()
defer v.mu.Unlock()
return append([]string(nil), v.uploads...), append([]string(nil), v.deletes...)
}
func (v *copyVolume) file() []byte {
v.mu.Lock()
defer v.mu.Unlock()
return v.stored
}
// sourceCutMidway makes the source send half of the chunk, then drop the
// connection.
const sourceCutMidway = -1
// newReassignCopyServer serves data as the source chunk (with ranges), or
// fails it with srcStatus, and assigns the copies to dsts in turn.
func newReassignCopyServer(t *testing.T, data []byte, srcStatus int, dsts ...*copyVolume) (*S3ApiServer, *reassignCopyFiler) {
t.Helper()
util_http.InitGlobalHttpClient()
src := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case srcStatus == sourceCutMidway:
// promise the whole chunk, send half of it, drop the connection
w.Header().Set("Content-Length", fmt.Sprint(len(data)))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(data[:len(data)/2])
w.(http.Flusher).Flush()
if conn, _, err := w.(http.Hijacker).Hijack(); err == nil {
conn.Close()
}
case srcStatus != 0:
http.Error(w, "source refused", srcStatus)
default:
http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(data))
}
}))
t.Cleanup(src.Close)
filer := &reassignCopyFiler{src: strings.TrimPrefix(src.URL, "http://"), dsts: dsts}
return newPutTestServer(t, startFakeFiler(t, filer)), filer
}
func testSSECKey(seed byte) *SSECustomerKey {
pair := GenerateTestSSECKey(seed)
return &SSECustomerKey{Algorithm: s3_constants.SSEAlgorithmAES256, Key: pair.Key, KeyMD5: pair.KeyMD5}
}
func sealSSEC(t *testing.T, plain []byte, key *SSECustomerKey) (sealed, iv []byte) {
t.Helper()
r, iv, err := CreateSSECEncryptedReader(bytes.NewReader(plain), key)
if err != nil {
t.Fatal(err)
}
if sealed, err = io.ReadAll(r); err != nil {
t.Fatal(err)
}
return sealed, iv
}
// openSSEC decrypts a stored SSE-C chunk with key and the IV chunk's metadata
// names, as a read of the copy would.
func openSSEC(t *testing.T, sealed []byte, chunk *filer_pb.FileChunk, key *SSECustomerKey) []byte {
t.Helper()
if chunk.SseType != filer_pb.SSEType_SSE_C {
t.Fatalf("the copied chunk is %v, want SSE-C", chunk.SseType)
}
meta, err := DeserializeSSECMetadata(chunk.SseMetadata)
if err != nil {
t.Fatal(err)
}
if meta.KeyMD5 != key.KeyMD5 {
t.Errorf("the copied chunk names key %s, want the destination key %s", meta.KeyMD5, key.KeyMD5)
}
iv, err := base64.StdEncoding.DecodeString(meta.IV)
if err != nil {
t.Fatal(err)
}
r, err := CreateSSECDecryptedReader(bytes.NewReader(sealed), key, iv)
if err != nil {
t.Fatal(err)
}
plain, err := io.ReadAll(r)
if err != nil {
t.Fatal(err)
}
return plain
}
// A copied chunk whose volume fails the write goes to another volume, as a
// PutObject chunk does, on every copy path, and the failed write's fid is
// deleted: the copy used to fail on the first such volume. The volume that
// takes it stores what the first one was sent, and the chunk names it.
func TestCopyChunkGoesToAnotherVolumeWhenItsVolumeFails(t *testing.T) {
data := bytes.Repeat([]byte("0123456789abcdef"), 4096)
const dstPath = "/buckets/b/k"
plain := &filer_pb.FileChunk{FileId: "7,01637037d6", Size: uint64(len(data))}
key := util.GenCipherKey()
ciphertext, err := util.Encrypt(data, key)
if err != nil {
t.Fatal(err)
}
cipher := &filer_pb.FileChunk{FileId: "7,01637037d6", Size: uint64(len(data)), CipherKey: key}
rangeChunk := &filer_pb.FileChunk{Offset: 0, Size: 1000}
rangeMd5 := md5.Sum(data[100:1100])
srcKey, dstKey := testSSECKey(1), testSSECKey(2)
sealed, srcIV := sealSSEC(t, data, srcKey)
srcMeta, err := SerializeSSECMetadata(srcIV, srcKey.KeyMD5, 0)
if err != nil {
t.Fatal(err)
}
ssec := &filer_pb.FileChunk{FileId: "7,01637037d6", Size: uint64(len(data)), SseType: filer_pb.SSEType_SSE_C, SseMetadata: srcMeta}
copyWhole := func(s3a *S3ApiServer) (*filer_pb.FileChunk, error) { return s3a.copySingleChunk(plain, dstPath) }
stores := func(want []byte, etag string) func(*testing.T, *filer_pb.FileChunk, []byte) {
return func(t *testing.T, dst *filer_pb.FileChunk, stored []byte) {
if !bytes.Equal(stored, want) {
t.Errorf("the second volume stored %d bytes, not the %d copied", len(stored), len(want))
}
if etag != "" && dst.ETag != etag {
t.Errorf("ETag %s, want %s: the retry must digest only the bytes it wrote", dst.ETag, etag)
}
}
}
cases := []struct {
name string
status int // how the first volume fails
outcome string // the write outcome it reports with status
copy func(s3a *S3ApiServer) (*filer_pb.FileChunk, error)
src []byte // the source chunk's stored bytes, data unless set
check func(t *testing.T, dst *filer_pb.FileChunk, stored []byte)
}{
{"streamed chunk, volume error", http.StatusInternalServerError, "", copyWhole, nil, stores(data, "")},
{"streamed chunk, connection lost", 0, "", copyWhole, nil, stores(data, "")},
{"streamed chunk, volume turned read-only before the append", http.StatusConflict, util_http.WriteOutcomeRefusedBeforeAppend, copyWhole, nil, stores(data, "")},
{"streamed chunk, token expired before the append", http.StatusUnauthorized, util_http.WriteOutcomeExpiredJwtBeforeAppend, copyWhole, nil, stores(data, "")},
{"streamed range", http.StatusInternalServerError, "", func(s3a *S3ApiServer) (*filer_pb.FileChunk, error) {
return s3a.copySingleChunkForRange(plain, rangeChunk, 100, 1099, dstPath)
}, nil, stores(data[100:1100], base64.StdEncoding.EncodeToString(rangeMd5[:]))},
{"buffered chunk", http.StatusInternalServerError, "", func(s3a *S3ApiServer) (*filer_pb.FileChunk, error) {
return s3a.copySingleChunk(cipher, dstPath)
}, ciphertext, stores(ciphertext, "")},
{"buffered chunk, volume turned read-only before the append", http.StatusConflict, util_http.WriteOutcomeRefusedBeforeAppend, func(s3a *S3ApiServer) (*filer_pb.FileChunk, error) {
return s3a.copySingleChunk(cipher, dstPath)
}, ciphertext, stores(ciphertext, "")},
{"SSE-C chunk re-encrypted under the destination key", http.StatusInternalServerError, "", func(s3a *S3ApiServer) (*filer_pb.FileChunk, error) {
chunk, _, err := s3a.copyMultipartSSECChunk(ssec, srcKey, dstKey, dstPath)
return chunk, err
}, sealed, func(t *testing.T, dst *filer_pb.FileChunk, stored []byte) {
if got := openSSEC(t, stored, dst, dstKey); !bytes.Equal(got, data) {
t.Error("the chunk the second volume stored does not decrypt to the source with the destination key and the IV the chunk names")
}
}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
bad, good := startCopyVolume(t, &copyVolume{status: c.status, outcome: c.outcome}), newCopyVolume(t, http.StatusCreated)
src := data
if c.src != nil {
src = c.src
}
s3a, filer := newReassignCopyServer(t, src, 0, bad, good)
dst, err := c.copy(s3a)
if err != nil {
t.Fatalf("copy: %v", err)
}
fids := filer.assigned()
if len(fids) != 2 {
t.Fatalf("assigned %v, want a second volume after the first failed", fids)
}
if dst.GetFileIdString() != fids[1] {
t.Errorf("the copied chunk names %s, want the volume it landed on, %s", dst.GetFileIdString(), fids[1])
}
if uploads, _ := good.got(); len(uploads) != 1 || uploads[0] != fids[1] {
t.Errorf("the second volume got %v, want [%s]", uploads, fids[1])
}
if _, deletes := bad.got(); len(deletes) != 1 || deletes[0] != fids[0] {
t.Errorf("the failed volume was asked to delete %v, want [%s]", deletes, fids[0])
}
c.check(t, dst, good.file())
})
}
}
// Only a failure of the destination volume is worth another one: a refusal
// another volume would repeat, or a source that cannot be read, fails the
// copy after the first volume.
func TestCopyChunkStaysOnItsVolumeWhenAnotherWouldNotHelp(t *testing.T) {
data := bytes.Repeat([]byte("x"), 1000)
plain := &filer_pb.FileChunk{FileId: "7,01637037d6", Size: uint64(len(data))}
cases := []struct {
name string
dstStatus int
srcStatus int
deletes int // a write that reached the volume is deleted; nothing else is
}{
{"volume refuses the request", http.StatusBadRequest, 0, 1},
{"conflict not marked as before the append", http.StatusConflict, 0, 1},
{"token refused, not marked as expired", http.StatusUnauthorized, 0, 1},
{"source unreadable", http.StatusCreated, http.StatusInternalServerError, 0},
{"source cut while streaming", http.StatusCreated, sourceCutMidway, 0},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
first, second := newCopyVolume(t, c.dstStatus), newCopyVolume(t, http.StatusCreated)
s3a, filer := newReassignCopyServer(t, data, c.srcStatus, first, second)
if _, err := s3a.copySingleChunk(plain, "/buckets/b/k"); err == nil {
t.Fatal("copy succeeded")
}
if fids := filer.assigned(); len(fids) != 1 {
t.Errorf("assigned %v, want one volume", fids)
}
if _, deletes := first.got(); len(deletes) != c.deletes {
t.Errorf("the volume was asked to delete %v, want %d", deletes, c.deletes)
}
})
}
}
// A chunk is offered to copyChunkAssignAttempts volumes at most, and to a
// second one only when the first was overloaded.
func TestCopyChunkReassignsBoundedTimes(t *testing.T) {
data := bytes.Repeat([]byte("x"), 1000)
plain := &filer_pb.FileChunk{FileId: "7,01637037d6", Size: uint64(len(data))}
cases := []struct {
name string
status int
want int
}{
{"failing volumes", http.StatusInternalServerError, copyChunkAssignAttempts},
{"overloaded volumes", http.StatusTooManyRequests, 2},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s3a, filer := newReassignCopyServer(t, data, 0, newCopyVolume(t, c.status))
if _, err := s3a.copySingleChunk(plain, "/buckets/b/k"); err == nil {
t.Fatal("copy succeeded")
}
if fids := filer.assigned(); len(fids) != c.want {
t.Errorf("assigned %d volumes %v, want %d", len(fids), fids, c.want)
}
})
}
}
// A failed volume that answers the cleanup delete and never finishes the
// answer holds the copy up for copyCleanupTimeout, not for good.
func TestCopyChunkCleanupDoesNotWaitOnAStalledVolume(t *testing.T) {
old := copyCleanupTimeout
copyCleanupTimeout = 100 * time.Millisecond
t.Cleanup(func() { copyCleanupTimeout = old })
data := bytes.Repeat([]byte("x"), 1000)
plain := &filer_pb.FileChunk{FileId: "7,01637037d6", Size: uint64(len(data))}
stalled := startCopyVolume(t, &copyVolume{status: http.StatusInternalServerError, stallDeletes: true})
s3a, filer := newReassignCopyServer(t, data, 0, stalled, newCopyVolume(t, http.StatusCreated))
type result struct {
dst *filer_pb.FileChunk
err error
}
done := make(chan result, 1)
go func() {
dst, err := s3a.copySingleChunk(plain, "/buckets/b/k")
done <- result{dst, err}
}()
var r result
select {
case r = <-done:
case <-time.After(10 * time.Second):
t.Fatal("the copy is still waiting on the cleanup of the stalled volume")
}
if r.err != nil {
t.Fatalf("copy: %v", r.err)
}
if fids := filer.assigned(); len(fids) != 2 || r.dst.GetFileIdString() != fids[1] {
t.Errorf("assigned %v and the chunk names %s, want it on the second volume", fids, r.dst.GetFileIdString())
}
if _, deletes := stalled.got(); len(deletes) != 1 {
t.Errorf("the stalled volume was asked to delete %v, want one fid", deletes)
}
}
// A failed copy can take longer than its write token lives, so the cleanup
// renews a token its holders refuse rather than leave the needle behind.
func TestDeleteFailedCopyChunkRenewsExpiredJwt(t *testing.T) {
var mu sync.Mutex
var tokens []string
holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
mu.Lock()
tokens = append(tokens, token)
mu.Unlock()
if token != "renewed" {
http.Error(w, "expired", http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusAccepted)
}))
t.Cleanup(holder.Close)
host := strings.TrimPrefix(holder.URL, "http://")
assignResult := &filer_pb.AssignVolumeResponse{FileId: "3,01637037d6", Auth: "expired", Location: &filer_pb.Location{Url: host}}
var lookedUp []string
deleteFailedCopyChunk(assignResult, func(_ context.Context, fileId string) security.EncodedJwt {
lookedUp = append(lookedUp, fileId)
return "renewed"
})
if want := []string{"3,01637037d6"}; fmt.Sprint(lookedUp) != fmt.Sprint(want) {
t.Fatalf("token lookups %v, want %v", lookedUp, want)
}
mu.Lock()
defer mu.Unlock()
if want := []string{"expired", "renewed"}; fmt.Sprint(tokens) != fmt.Sprint(want) {
t.Fatalf("delete tokens %v, want %v", tokens, want)
}
}