Files
seaweedfs/weed/s3api/s3api_circuit_breaker.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

326 lines
11 KiB
Go

package s3api
import (
"context"
"errors"
"fmt"
"net/http"
"sync"
"sync/atomic"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/util"
)
type CircuitBreaker struct {
sync.RWMutex
Enabled bool
counters map[string]*int64
limitations map[string]int64
s3a *S3ApiServer
// Interceptor, if set, wraps the per-route handler ahead of ALL
// circuit-breaker logic (upload limiting and the breaker checks) and runs
// even when the breaker is disabled. It is a general per-request
// interceptor seam: an implementation may reject the request (write its own
// response and not call next) or wrap next to observe/shape it. Nil by
// default, so it is a no-op unless explicitly set.
Interceptor func(next http.HandlerFunc, action string) http.HandlerFunc
}
func NewCircuitBreaker(option *S3ApiServerOption) *CircuitBreaker {
cb := &CircuitBreaker{
counters: make(map[string]*int64),
limitations: make(map[string]int64),
}
// Use WithOneOfGrpcFilerClients to support multiple filers with failover
err := pb.WithOneOfGrpcFilerClients(false, option.Filers, option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
content, err := filer.ReadInsideFiler(context.Background(), client, s3_constants.CircuitBreakerConfigDir, s3_constants.CircuitBreakerConfigFile)
if errors.Is(err, filer_pb.ErrNotFound) {
return nil
}
if err != nil {
return fmt.Errorf("read S3 circuit breaker config: %w", err)
}
return cb.LoadS3ApiConfigurationFromBytes(content)
})
if err != nil {
glog.Warningf("S3 circuit breaker disabled; failed to load config from any filer: %v", err)
}
return cb
}
func (cb *CircuitBreaker) LoadS3ApiConfigurationFromBytes(content []byte) error {
cbCfg := &s3_pb.S3CircuitBreakerConfig{}
if err := filer.ParseS3ConfigurationFromBytes(content, cbCfg); err != nil {
glog.Warningf("unmarshal error: %v", err)
return fmt.Errorf("unmarshal error: %w", err)
}
if err := cb.loadCircuitBreakerConfig(cbCfg); err != nil {
return err
}
return nil
}
func (cb *CircuitBreaker) loadCircuitBreakerConfig(cfg *s3_pb.S3CircuitBreakerConfig) error {
//global
globalEnabled := false
globalOptions := cfg.Global
limitations := make(map[string]int64)
if globalOptions != nil && globalOptions.Enabled && len(globalOptions.Actions) > 0 {
globalEnabled = globalOptions.Enabled
for action, limit := range globalOptions.Actions {
limitations[action] = limit
}
}
cb.Enabled = globalEnabled
//buckets
for bucket, cbOptions := range cfg.Buckets {
if cbOptions.Enabled {
for action, limit := range cbOptions.Actions {
limitations[s3_constants.Concat(bucket, action)] = limit
}
}
}
cb.limitations = limitations
return nil
}
func (cb *CircuitBreaker) Limit(f func(w http.ResponseWriter, r *http.Request), action string) (http.HandlerFunc, Action) {
inner := func(w http.ResponseWriter, r *http.Request) {
// Apply upload limiting for write actions if configured
if cb.s3a != nil && (action == s3_constants.ACTION_WRITE) &&
(cb.s3a.option.ConcurrentUploadLimit != 0 || cb.s3a.option.ConcurrentFileUploadLimit != 0) {
charged := cb.uploadCharge(r)
if !cb.waitForUploadSlot(w, r, charged) {
return
}
defer func() {
cb.s3a.inFlightDataLimitCond.L.Lock()
defer cb.s3a.inFlightDataLimitCond.L.Unlock()
// Decrement counters
newUploads := atomic.AddInt64(&cb.s3a.inFlightUploads, -1)
newSize := atomic.AddInt64(&cb.s3a.inFlightDataSize, -charged)
// Update metrics
stats.S3InFlightUploadCountGauge.Set(float64(newUploads))
stats.S3InFlightUploadBytesGauge.Set(float64(newSize))
cb.s3a.inFlightDataLimitCond.Broadcast()
}()
}
// Apply circuit breaker logic
if !cb.Enabled {
f(w, r)
return
}
vars := mux.Vars(r)
bucket := vars["bucket"]
rollback, errCode := cb.limit(r, bucket, action)
defer func() {
for _, rf := range rollback {
rf()
}
}()
if errCode == s3err.ErrNone {
f(w, r)
return
}
s3err.WriteErrorResponse(w, r, errCode)
}
// The interceptor is consulted per request rather than captured here, so it
// can be installed after the routes are registered (e.g. once the server and
// its dependencies are constructed) and so a nil CircuitBreaker is never
// dereferenced at registration time. When unset this is just a nil check.
// It runs outermost: before upload limiting and the breaker checks, and
// regardless of cb.Enabled.
return func(w http.ResponseWriter, r *http.Request) {
if cb.Interceptor != nil {
cb.Interceptor(inner, action)(w, r)
return
}
inner(w, r)
}, Action(action)
}
// declaredUploadSize is the body length r declares: Content-Length, or, for an
// aws-chunked body only, X-Amz-Decoded-Content-Length when Content-Length is
// unknown, so a client-controlled header cannot lower what a request that
// declares its length is charged. getRequestDataReader holds an aws-chunked
// body to that length; no other body is decoded, so for one the header proves
// nothing and is ignored. -1 when neither is known.
func declaredUploadSize(r *http.Request) int64 {
declared := r.ContentLength
if declared < 0 && isAwsChunkedUpload(r) {
if decoded, ok := decodedContentLength(r); ok {
declared = decoded
}
}
return declared
}
// uploadCharge is the bytes r reserves against the in-flight upload budget;
// see util.GatewayUploadCharge.
func (cb *CircuitBreaker) uploadCharge(r *http.Request) int64 {
return util.GatewayUploadCharge(declaredUploadSize(r), int64(cb.s3a.uploadChunkSize()), cb.s3a.option.ConcurrentUploadLimit)
}
// waitForUploadSlot reserves charged bytes and one upload slot, or writes the
// rejection and returns false. The caller releases exactly charged.
func (cb *CircuitBreaker) waitForUploadSlot(w http.ResponseWriter, r *http.Request, charged int64) bool {
s3a := cb.s3a
s3a.inFlightDataLimitCond.L.Lock()
err := util.WaitUntil(r.Context(), s3a.inFlightDataLimitCond, s3a.option.InflightUploadDataTimeout, func() bool {
inFlightDataSize := atomic.LoadInt64(&s3a.inFlightDataSize)
if !util.UploadAdmits(inFlightDataSize, charged, s3a.option.ConcurrentUploadLimit) {
glog.V(4).Infof("wait because inflight data %d + %d > %d", inFlightDataSize, charged, s3a.option.ConcurrentUploadLimit)
return false
}
inFlightUploads := atomic.LoadInt64(&s3a.inFlightUploads)
if s3a.option.ConcurrentFileUploadLimit != 0 && inFlightUploads >= s3a.option.ConcurrentFileUploadLimit {
glog.V(4).Infof("wait because inflight uploads %d >= %d", inFlightUploads, s3a.option.ConcurrentFileUploadLimit)
return false
}
return true
})
if err == nil {
// Increment counters
newUploads := atomic.AddInt64(&s3a.inFlightUploads, 1)
newSize := atomic.AddInt64(&s3a.inFlightDataSize, charged)
// Update metrics
stats.S3InFlightUploadCountGauge.Set(float64(newUploads))
stats.S3InFlightUploadBytesGauge.Set(float64(newSize))
}
s3a.inFlightDataLimitCond.L.Unlock()
if err == nil {
return true
}
// Reject without reading the body: draining it would send an
// Expect: 100-continue client the go-ahead, and closing an HTTP/1
// connection stops net/http from reading it before the reply.
if r.ProtoMajor == 1 {
w.Header().Set("Connection", "close")
}
rejected := r.WithContext(r.Context())
rejected.Body = http.NoBody
if r.Context().Err() != nil {
glog.V(1).Infof("upload from %s cancelled while waiting for an upload slot: %v", r.RemoteAddr, err)
s3err.WriteErrorResponse(w, rejected, s3err.ErrClientDisconnected)
return false
}
glog.V(1).Infof("reject upload from %s: no upload slot within %v", r.RemoteAddr, s3a.option.InflightUploadDataTimeout)
s3err.WriteErrorResponse(w, rejected, s3err.ErrTooManyRequest)
return false
}
func (cb *CircuitBreaker) limit(r *http.Request, bucket string, action string) (rollback []func(), errCode s3err.ErrorCode) {
// The byte counters count what the request declares, as they always have,
// so a bucket bytes limit still rejects one PUT larger than it. An unknown
// length counts one chunk rather than -1, which would decrement them; the
// same value is added and rolled back.
requestBytes := max(r.ContentLength, 0)
if cb.s3a != nil {
requestBytes = util.CountedUploadSize(declaredUploadSize(r), int64(cb.s3a.uploadChunkSize()))
}
//bucket simultaneous request count
bucketCountRollBack, errCode := cb.loadCounterAndCompare(s3_constants.Concat(bucket, action, s3_constants.LimitTypeCount), 1, s3err.ErrTooManyRequest)
if bucketCountRollBack != nil {
rollback = append(rollback, bucketCountRollBack)
}
if errCode != s3err.ErrNone {
return
}
//bucket simultaneous request content bytes
bucketContentLengthRollBack, errCode := cb.loadCounterAndCompare(s3_constants.Concat(bucket, action, s3_constants.LimitTypeBytes), requestBytes, s3err.ErrRequestBytesExceed)
if bucketContentLengthRollBack != nil {
rollback = append(rollback, bucketContentLengthRollBack)
}
if errCode != s3err.ErrNone {
return
}
//global simultaneous request count
globalCountRollBack, errCode := cb.loadCounterAndCompare(s3_constants.Concat(action, s3_constants.LimitTypeCount), 1, s3err.ErrTooManyRequest)
if globalCountRollBack != nil {
rollback = append(rollback, globalCountRollBack)
}
if errCode != s3err.ErrNone {
return
}
//global simultaneous request content bytes
globalContentLengthRollBack, errCode := cb.loadCounterAndCompare(s3_constants.Concat(action, s3_constants.LimitTypeBytes), requestBytes, s3err.ErrRequestBytesExceed)
if globalContentLengthRollBack != nil {
rollback = append(rollback, globalContentLengthRollBack)
}
if errCode != s3err.ErrNone {
return
}
return
}
func (cb *CircuitBreaker) loadCounterAndCompare(key string, inc int64, errCode s3err.ErrorCode) (f func(), e s3err.ErrorCode) {
e = s3err.ErrNone
if max, ok := cb.limitations[key]; ok {
cb.RLock()
counter, exists := cb.counters[key]
cb.RUnlock()
if !exists {
cb.Lock()
counter, exists = cb.counters[key]
if !exists {
var newCounter int64
counter = &newCounter
cb.counters[key] = counter
}
cb.Unlock()
}
current := atomic.LoadInt64(counter)
if current+inc > max {
e = errCode
return
} else {
current := atomic.AddInt64(counter, inc)
f = func() {
atomic.AddInt64(counter, -inc)
}
if current > max {
e = errCode
return
}
}
}
return
}
func (s3a *S3ApiServer) Limit(handler http.HandlerFunc, action string) http.HandlerFunc {
if s3a.cb == nil {
return handler
}
limited, _ := s3a.cb.Limit(handler, action)
return limited
}