Files
seaweedfs/weed/s3api/s3api_handlers_failover_test.go
T
77a6787335 Bound upload memory: admission by size, gateway holder writes, 503/SlowDown back-pressure, body deadline (#13021)
* util: one admission rule for upload limits

* operation: mark gateway fan-out holder writes as client traffic

* volume: bound upload admission, limit gateway holder writes, 503 on timeout

* volume: charge unknown-length uploads half the budget, document client wait cap

* s3, filer: admit uploads by inFlight+size and charge unknown lengths a chunk

* s3: answer a volume overload as SlowDown with Retry-After

* operation: cut an upload whose body crawls below the minimum rate on any host

* operation: make the slow-commit deadline test honour the request context

* s3: stop chunk uploads when the client goes away

* operation: treat a body deadline cut as back-pressure, not a same-holder retry

A body that crawls past the body deadline returns from retriedUploadData at
once, like an overload, and counts toward the single reassign the chunk loop
and the filer retry gate give back-pressure. A watchdog cut keeps its retry on
a fresh conn. Both still match ErrUploadStalled and stay reassignable.

* operation: apply the body deadline only to uploads that opt in

UploadOption.BodyDeadline and ChunkedUploadOption.BodyDeadline turn the
body deadline on; S3 chunk uploads (relay and fan-out) and the filer's chunk
loop set it. Mount, filer.sync, filer.copy and UploadWithRetry keep the stall
watchdog only, as before the deadline existed.

* s3, operation: check a chunk cancelled with its client is deleted from every holder

A volume commits on a context that ignores the cancel, so a chunk whose
caller went away after sending the body may still land. The chunk loop
already deletes the fid from every holder after a failed attempt; pin that
for the relay and fan-out paths and for an S3 PUT whose client goes away.

* s3: count a request's declared bytes in the circuit breaker byte limits

The per-bucket and global byte counters go back to the declared length (an
unknown length counts one chunk), so a bucket bytes limit still rejects a
single PUT larger than it. Only the upload budget uses the capped gateway
charge.

* s3: answer copy chunk overloads as SlowDown, tidy the client-gone checks

CopyObject and UploadPartCopy map a volume overload or an exhausted stall to
SlowDown, as PutObject does. The client-gone log check matches the mapper's
context.Canceled test, the truncated-body case drops a check the first case
already makes, and the Retry-After test reads the headers actually sent.

* filer, volume: clamp the filer charge chunk, set the upload gauge under the lock

A filer with -maxMB 0 charges its default chunk size instead of nothing. The
volume server sets its in-flight upload gauge inside the critical section.
The upload limit tests wait until the waiter is parked before releasing,
check handleUploadRequest gives its charge back, and use CI-safe bounds.

* volume: cap the Rust server's client upload-slot wait at 5s

Same cap as the Go volume server's volumeClientUploadWaitCap, so a gateway's
body deadline never fires before the 503.

* operation: reflow the body deadline comment

* volume(rs): count a gateway's src=client holder write against the upload limit

Mirrors operation.IsReplicaForward: only a primary-to-replica forward
skips the upload budget; a gateway's ?type=replicate&src=client fan-out
waits like any client write.

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

* volume(rs): admit uploads by inFlight+size, reserved atomically

Mirrors the Go volume server's waitForUploadSlot: an upload is admitted
by util.UploadAdmits (idle server, or inFlight + size within the limit)
and reserves its bytes in the same step, so concurrent waiters cannot
all pass one check. Primary-to-replica forwards and unlimited servers
are counted but never refused. UploadLimitCond counts once per waiting
upload, and the wake-up is armed before each check so a release in
between is not missed.

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

* volume(rs): charge an unknown-length upload against the upload limit

Mirrors the Go volume server's uploadCharge: a chunked upload without
Content-Length reserves one file's worth of budget, at most half the
limit and at least 1 byte, instead of 0.

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

* volume(rs): a zero -inflightUploadDataTimeout waits the 5s client cap

The Go volume server now reads 0 as the 5s cap (its flag help says so);
the Rust server used a 2s wait.

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

* volume(rs): close a rejected large or unknown-length HTTP/1 upload

Mirrors the Go volume server's uploadRejectCloseThreshold: the 503 for
a body over 256 KiB, or one without a length, carries Connection: close
instead of keeping the connection for a body nobody reads.

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

* volume(rs): drop src from a primary's replica forward

A client upload carrying src=client kept it on the forward, so replicas
treated the forward as gateway fan-out and could refuse it after the
primary had already appended. Go's ReplicatedWrite builds a fresh query.

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

* volume(rs): keep the upload admission CAS buildable on rust 1.91.1

Atomic try_update is stable only since 1.95.

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

* volume(rs): refuse an upload the in-flight counter cannot hold

A replica forward added its charge with fetch_add, so a Content-Length
near i64::MAX wrapped the shared counter negative and let later client
uploads past admission. The forward now reserves with a checked add and
answers 503 when the size does not fit; the client CAS adds only after
admission passes. With no upload limit the counter only feeds the gauge,
so it keeps wrapping arithmetic.

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

* volume: refuse an upload the in-flight counter cannot hold

A replica forward added its charge unchecked, so a Content-Length near
math.MaxInt64 wrapped inFlightUploadDataSize negative and let later
client uploads past admission. Under the lock the reservation now
checks that the counter can hold the charge and answers 503 otherwise,
matching the Rust volume server.

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

* volume: keep the request body on a rejected upload

Replacing r.Body with http.NoBody hid the server's early close of the
unread body from net/http before Go 1.27, so it skipped the FIN-then-wait
close and reset the connection under a client still sending. Go 1.26.6,
the version go.mod declares, then failed
TestUploadLimit503ReachesGoClientForLargeBody with a write error instead of
the 503.

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

* util: compare upload admission without forming inFlight+size

* operation: reassign a chunk after a 429 as after a 503

* s3: do not count a chunk assignment the client cancelled as a filer failure

* filer: charge an upload by its request chunk size, and an inline upload by its whole body

* s3: hold an aws-chunked body to its X-Amz-Decoded-Content-Length

* volume: answer a rejected small-body upload without waiting for its body

* s3: fill the upload budget before testing that a release wakes every waiter

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:34:47 -08:00

235 lines
8.2 KiB
Go

package s3api
import (
"context"
"io"
"math"
"reflect"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
)
// fakeListFiler serves ListEntries from names; the first failCalls calls die
// with Unavailable after streaming sendBeforeFail entries.
type fakeListFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
names []string
failCalls int32
sendBeforeFail int
calls int32
}
func (f *fakeListFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
names := f.names
failing := atomic.AddInt32(&f.calls, 1) <= f.failCalls
if failing {
names = names[:f.sendBeforeFail]
}
for _, name := range names {
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: &filer_pb.Entry{Name: name}}); err != nil {
return err
}
}
if failing {
return status.Error(codes.Unavailable, "filer restarting")
}
return nil
}
func newFailoverTestServer(t *testing.T, filers ...pb.ServerAddress) *S3ApiServer {
t.Helper()
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
return &S3ApiServer{
option: &S3ApiServerOption{Filers: filers, GrpcDialOption: dialOption},
filerClient: wdclient.NewFilerClient(filers, dialOption, ""),
}
}
// accumulateListing is the callback shape the failover contract has to protect:
// entries collect into a variable that survives a replay of the callback.
func accumulateListing(got *[]string) func(filer_pb.SeaweedFilerClient) error {
return func(client filer_pb.SeaweedFilerClient) error {
stream, err := client.ListEntries(context.Background(), &filer_pb.ListEntriesRequest{Directory: "/d"})
if err != nil {
return err
}
for {
resp, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
*got = append(*got, resp.Entry.Name)
}
}
}
// A filer that dies mid-stream must surface the error, not fail over: the
// callback has already consumed part of the response, and replaying it against
// the next filer would append a second copy of what it accumulated.
func TestFailoverStopsAfterPartialResponse(t *testing.T) {
names := []string{"e1", "e2", "e3", "e4"}
flaky := &fakeListFiler{names: names, failCalls: math.MaxInt32, sendBeforeFail: 2}
healthy := &fakeListFiler{names: names}
s3a := newFailoverTestServer(t, startFakeFiler(t, flaky), startFakeFiler(t, healthy))
var got []string
err := s3a.WithFilerClient(true, accumulateListing(&got))
if err == nil {
t.Fatalf("want the mid-stream failure surfaced, got success with %v", got)
}
if calls := atomic.LoadInt32(&healthy.calls); calls != 0 {
t.Fatalf("callback was replayed on the second filer %d time(s)", calls)
}
}
// A filer that fails before delivering anything is still failed over, so the
// partial-response guard does not cost the healthy-peer retry that failover exists for.
func TestFailoverBeforeFirstResponse(t *testing.T) {
names := []string{"e1", "e2", "e3", "e4"}
flaky := &fakeListFiler{names: names, failCalls: math.MaxInt32, sendBeforeFail: 0}
healthy := &fakeListFiler{names: names}
s3a := newFailoverTestServer(t, startFakeFiler(t, flaky), startFakeFiler(t, healthy))
var got []string
err := s3a.WithFilerClient(true, accumulateListing(&got))
if err != nil {
t.Fatalf("want failover success, got %v", err)
}
if !reflect.DeepEqual(got, names) {
t.Fatalf("entries = %v, want %v", got, names)
}
}
// End to end through the real listing path: a mid-stream failure surfaces to
// listWithRetry, whose replay starts from a fresh accumulator, so the caller
// sees each entry exactly once instead of a silently duplicated prefix.
func TestListAfterMidStreamFailureHasNoDuplicates(t *testing.T) {
names := []string{"e1", "e2", "e3", "e4"}
flaky := &fakeListFiler{names: names, failCalls: 1, sendBeforeFail: 2}
healthy := &fakeListFiler{names: names}
s3a := newFailoverTestServer(t, startFakeFiler(t, flaky), startFakeFiler(t, healthy))
entries, isLast, err := s3a.list("/d", "", "", false, 10)
if err != nil {
t.Fatalf("list: %v", err)
}
var got []string
for _, entry := range entries {
got = append(got, entry.Name)
}
if !reflect.DeepEqual(got, names) {
t.Fatalf("entries = %v, want %v", got, names)
}
if !isLast {
t.Fatal("want isLast")
}
}
// hangingCollectionFiler answers CollectionList only when the caller gives up,
// standing in for a filer waiting on a master that has stopped answering.
type hangingCollectionFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
calls atomic.Int32
}
func (f *hangingCollectionFiler) CollectionList(ctx context.Context, _ *filer_pb.CollectionListRequest) (*filer_pb.CollectionListResponse, error) {
f.calls.Add(1)
<-ctx.Done()
return nil, ctx.Err()
}
// The caller's own budget expiring says nothing about the filer that was
// answering it. Counted as a filer failure it would, after the three that open
// the circuit, mark every filer in the walk unhealthy -- and LookupVolumeIds
// skips unhealthy filers, so unrelated object reads would start failing over a
// slow master they never touched.
func TestFailoverDoesNotBlameFilersForTheCallersExpiredBudget(t *testing.T) {
first := &hangingCollectionFiler{}
second := &hangingCollectionFiler{}
firstAddr := startFakeFiler(t, first)
secondAddr := startFakeFiler(t, second)
s3a := newFailoverTestServer(t, firstAddr, secondAddr)
// More attempts than the three failures it takes to open the circuit.
for attempt := 0; attempt < 5; attempt++ {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
err := s3a.withFilerClient(ctx, false, func(client filer_pb.SeaweedFilerClient) error {
_, listErr := client.CollectionList(ctx, &filer_pb.CollectionListRequest{})
return listErr
})
cancel()
if err == nil {
t.Fatalf("attempt %d: want the expired budget surfaced as an error", attempt)
}
}
for _, addr := range []pb.ServerAddress{firstAddr, secondAddr} {
if s3a.filerClient.ShouldSkipUnhealthyFiler(addr) {
t.Errorf("filer %s was flagged unhealthy for the caller's own timeout; unrelated reads would now skip it", addr)
}
}
// And the walk stops rather than spending an already-spent budget on the next
// filer, which cannot answer any faster.
if n := second.calls.Load(); n != 0 {
t.Errorf("the second filer was tried %d times with no budget left to answer in", n)
}
}
// hangingAssignFiler answers AssignVolume only when the caller gives up,
// standing in for a filer still waiting on the master for a volume.
type hangingAssignFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
calls atomic.Int32
}
func (f *hangingAssignFiler) AssignVolume(ctx context.Context, _ *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) {
f.calls.Add(1)
<-ctx.Done()
return nil, ctx.Err()
}
// An S3 client that disconnects while its chunk waits for a volume cancels the
// assignment. That cancel must not count against the filer, or a few clients
// going away would open the circuit on healthy filers, and it must not send the
// same dead request on to the next filer.
func TestAssignUploadVolumeDoesNotBlameFilersForAClientThatLeft(t *testing.T) {
first := &hangingAssignFiler{}
second := &hangingAssignFiler{}
firstAddr := startFakeFiler(t, first)
secondAddr := startFakeFiler(t, second)
s3a := newFailoverTestServer(t, firstAddr, secondAddr)
// More attempts than the three failures it takes to open the circuit.
for attempt := 0; attempt < 5; attempt++ {
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(50*time.Millisecond, cancel)
_, err := s3a.assignUploadVolume(ctx, &filer_pb.AssignVolumeRequest{Count: 1})
cancel()
if err == nil {
t.Fatalf("attempt %d: want the cancelled assignment surfaced as an error", attempt)
}
}
for _, addr := range []pb.ServerAddress{firstAddr, secondAddr} {
if s3a.filerClient.ShouldSkipUnhealthyFiler(addr) {
t.Errorf("filer %s was flagged unhealthy because the client went away", addr)
}
}
if n := second.calls.Load(); n != 0 {
t.Errorf("the second filer was asked %d times for a client that had already gone", n)
}
}