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

224 lines
9.2 KiB
Go

package s3api
import (
"errors"
"fmt"
"net/http"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/operation"
"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"
weed_server "github.com/seaweedfs/seaweedfs/weed/server"
)
// executeUnifiedCopyStrategy executes the appropriate copy strategy based on encryption state
// Returns chunks and destination metadata that should be applied to the destination entry.
// replacesSource says the destination entry is the source entry, which is what lets the
// key-rotation strategy hand back the source chunks instead of copying them.
func (s3a *S3ApiServer) executeUnifiedCopyStrategy(entry *filer_pb.Entry, r *http.Request, srcBucket, dstBucket, srcObject, dstObject string, replacesSource bool) ([]*filer_pb.FileChunk, map[string][]byte, error) {
// Per-chunk copy must see data chunks: a manifest chunk copied raw becomes
// object data. Resolved manifests stay with the source.
if _, err := s3a.flattenManifestChunks(r.Context(), entry); err != nil {
return nil, nil, fmt.Errorf("resolve source manifest chunks: %w", err)
}
// Detect encryption state (using entry-aware detection for multipart objects)
srcPath := fmt.Sprintf("%s/%s", s3a.bucketDir(srcBucket), srcObject)
dstPath := fmt.Sprintf("%s/%s", s3a.bucketDir(dstBucket), dstObject)
state := DetectEncryptionStateWithEntry(entry, r, srcPath, dstPath)
// Debug logging for encryption state
// Apply bucket default encryption if no explicit encryption specified
s3a.applyCopyBucketDefaultEncryption(state, dstBucket)
// Determine copy strategy
strategy, err := DetermineUnifiedCopyStrategy(state, entry.Extended, r)
if err != nil {
return nil, nil, err
}
glog.V(2).Infof("Unified copy strategy for %s → %s: %v", srcPath, dstPath, strategy)
// Calculate optimized sizes for the strategy
sizeCalc := CalculateOptimizedSizes(entry, r, strategy)
glog.V(2).Infof("Size calculation: src=%d, target=%d, actual=%d, overhead=%d, preallocate=%v",
sizeCalc.SourceSize, sizeCalc.TargetSize, sizeCalc.ActualContentSize,
sizeCalc.EncryptionOverhead, sizeCalc.CanPreallocate)
// Execute strategy
switch strategy {
case CopyStrategyDirect:
chunks, err := s3a.copyChunks(entry, dstPath)
return chunks, nil, err
case CopyStrategyKeyRotation:
return s3a.executeKeyRotation(entry, r, state, dstBucket, dstPath, replacesSource)
case CopyStrategyEncrypt:
return s3a.executeEncryptCopy(entry, r, state, dstBucket, dstPath)
case CopyStrategyDecrypt:
return s3a.executeDecryptCopy(entry, r, state, dstPath)
case CopyStrategyReencrypt:
return s3a.executeReencryptCopy(entry, r, state, dstBucket, dstPath)
default:
return nil, nil, fmt.Errorf("unknown unified copy strategy: %v", strategy)
}
}
// mapCopyErrorToS3Error maps various copy errors to appropriate S3 error codes
func (s3a *S3ApiServer) mapCopyErrorToS3Error(err error) s3err.ErrorCode {
if err == nil {
return s3err.ErrNone
}
// Check for read-only errors (quota enforcement)
// Uses errors.Is() to properly detect wrapped errors
if errors.Is(err, weed_server.ErrReadOnly) {
// Bucket is read-only due to quota enforcement or other configuration
// Return 403 Forbidden per S3 semantics (similar to MinIO's quota enforcement)
return s3err.ErrAccessDenied
}
// A destination volume short of upload budget, or a chunk write that
// stalled through its retries, is load the client should back off from:
// SlowDown, as for PutObject, not a 500 it cannot tell from a fault.
if operation.IsUploadOverloaded(err) || errors.Is(err, operation.ErrUploadStalled) {
return s3err.ErrTooManyRequest
}
// Check for KMS errors first
if kmsErr := MapKMSErrorToS3Error(err); kmsErr != s3err.ErrInvalidRequest {
return kmsErr
}
// Check for SSE-C errors
if ssecErr := MapSSECErrorToS3Error(err); ssecErr != s3err.ErrInvalidRequest {
return ssecErr
}
// Default to internal error for unknown errors
return s3err.ErrInternalError
}
// executeKeyRotation handles key rotation for same-object copies
func (s3a *S3ApiServer) executeKeyRotation(entry *filer_pb.Entry, r *http.Request, state *EncryptionState, dstBucket, dstPath string, replacesSource bool) ([]*filer_pb.FileChunk, map[string][]byte, error) {
// For key rotation, we only need to update metadata, not re-copy chunks
// This is a significant optimization for same-object key changes
if state.SrcSSEC && state.DstSSEC {
// SSE-C key rotation - need to handle new key/IV, use reencrypt logic
return s3a.executeReencryptCopy(entry, r, state, dstBucket, dstPath)
}
// Handing back the source chunks leaves the destination sharing needles nothing
// refcounts, so it is only safe when the destination overwrites the source entry.
// A versioned rotation writes a new version beside the source and has to reencrypt.
if state.SrcSSEKMS && state.DstSSEKMS && replacesSource {
// SSE-KMS key rotation - return existing chunks, metadata will be updated by caller
return entry.GetChunks(), nil, nil
}
// Fallback to reencrypt if we can't do metadata-only rotation
return s3a.executeReencryptCopy(entry, r, state, dstBucket, dstPath)
}
// executeEncryptCopy handles plain → encrypted copies
func (s3a *S3ApiServer) executeEncryptCopy(entry *filer_pb.Entry, r *http.Request, state *EncryptionState, dstBucket, dstPath string) ([]*filer_pb.FileChunk, map[string][]byte, error) {
if state.DstSSEC {
// Use existing SSE-C copy logic
return s3a.copyChunksWithSSEC(entry, r, dstPath)
}
if state.DstSSEKMS {
// Use existing SSE-KMS copy logic - metadata is now generated internally
chunks, dstMetadata, err := s3a.copyChunksWithSSEKMS(entry, r, dstBucket, dstPath)
return chunks, dstMetadata, err
}
if state.DstSSES3 {
// Use chunk-by-chunk copy for SSE-S3 encryption (consistent with SSE-C and SSE-KMS)
glog.V(2).Infof("Plain→SSE-S3 copy: using unified multipart encrypt copy")
return s3a.copyMultipartCrossEncryption(entry, r, state, dstBucket, dstPath)
}
return nil, nil, fmt.Errorf("unknown target encryption type")
}
// executeDecryptCopy handles encrypted → plain copies
func (s3a *S3ApiServer) executeDecryptCopy(entry *filer_pb.Entry, r *http.Request, state *EncryptionState, dstPath string) ([]*filer_pb.FileChunk, map[string][]byte, error) {
// Use unified multipart-aware decrypt copy for all encryption types (consistent chunk-by-chunk)
if state.SrcSSEC || state.SrcSSEKMS || state.SrcSSES3 {
glog.V(2).Infof("Encrypted→Plain copy: using unified multipart decrypt copy")
return s3a.copyMultipartCrossEncryption(entry, r, state, "", dstPath)
}
return nil, nil, fmt.Errorf("unknown source encryption type")
}
// executeReencryptCopy handles encrypted → encrypted copies with different keys/methods
func (s3a *S3ApiServer) executeReencryptCopy(entry *filer_pb.Entry, r *http.Request, state *EncryptionState, dstBucket, dstPath string) ([]*filer_pb.FileChunk, map[string][]byte, error) {
// Use chunk-by-chunk approach for all cross-encryption scenarios (consistent behavior)
if state.SrcSSEC && state.DstSSEC {
return s3a.copyChunksWithSSEC(entry, r, dstPath)
}
if state.SrcSSEKMS && state.DstSSEKMS {
// Use existing SSE-KMS copy logic - metadata is now generated internally
chunks, dstMetadata, err := s3a.copyChunksWithSSEKMS(entry, r, dstBucket, dstPath)
return chunks, dstMetadata, err
}
// All other cross-encryption scenarios use unified multipart copy
// This includes: SSE-C↔SSE-KMS, SSE-C↔SSE-S3, SSE-KMS↔SSE-S3, SSE-S3↔SSE-S3
glog.V(2).Infof("Cross-encryption copy: using unified multipart copy")
return s3a.copyMultipartCrossEncryption(entry, r, state, dstBucket, dstPath)
}
// applyCopyBucketDefaultEncryption applies the destination bucket's default encryption settings if no explicit encryption is specified
func (s3a *S3ApiServer) applyCopyBucketDefaultEncryption(state *EncryptionState, dstBucket string) {
if !state.IsTargetEncrypted() {
bucketMetadata, err := s3a.getBucketMetadata(dstBucket)
if err == nil && bucketMetadata != nil && bucketMetadata.Encryption != nil {
switch bucketMetadata.Encryption.SseAlgorithm {
case "aws:kms":
state.DstSSEKMS = true
case "AES256":
state.DstSSES3 = true
}
}
}
}
// applyCopyBucketDefaultEncryptionHeaders surfaces a bucket's default
// encryption as request headers, so multi-chunk copy paths that only read
// request headers honor it too.
func applyCopyBucketDefaultEncryptionHeaders(r *http.Request, cfg *s3_pb.EncryptionConfiguration) {
if cfg == nil {
return
}
switch cfg.SseAlgorithm {
case EncryptionTypeKMS:
r.Header.Set(s3_constants.AmzServerSideEncryption, "aws:kms")
// aws:kms with no configured key resolves the AWS default, the same
// fallback applySSEKMSDefaultEncryption uses for uploads; an empty
// key ID here would let the copy paths take their plaintext branch.
keyID := cfg.KmsKeyId
if keyID == "" {
keyID = s3_constants.SSEKMSDefaultKeyID
}
r.Header.Set(s3_constants.AmzServerSideEncryptionAwsKmsKeyId, keyID)
if cfg.BucketKeyEnabled {
r.Header.Set(s3_constants.AmzServerSideEncryptionBucketKeyEnabled, "true")
}
case EncryptionTypeAES256:
r.Header.Set(s3_constants.AmzServerSideEncryption, "AES256")
}
}