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

160 lines
6.7 KiB
Go

package s3api
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"time"
"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/security"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// copyChunkAssignAttempts bounds how many volumes one copied chunk may be
// offered to, as PutObject bounds each of its chunks.
const copyChunkAssignAttempts = 3
// copyUploadError marks a failure of the destination volume while a copied
// chunk was written to it, the only kind another volume can cure; a copy that
// could not read its source is not one. An error from the uploader carries its
// own status; a streamed copy's POST records the volume server's HTTP status,
// 0 when no response came back, and its write outcome header.
type copyUploadError struct {
fromUploader bool
status int
outcome string
err error
}
func (e *copyUploadError) Error() string { return e.err.Error() }
func (e *copyUploadError) Unwrap() error { return e.err }
// reassignable reports whether another volume might take a chunk whose upload
// failed with err, and whether the failure is back-pressure, which earns one
// fresh volume only. The uploader's errors are judged as PutObject judges its
// chunks' (operation.ShouldReassignUpload); a streamed POST by its status the
// same way: a transport failure, a 5xx, an overload refusal, or a 409 or 401
// the volume marked as made before it appended the needle (a volume turned
// read-only, a token expired in the queue).
func reassignable(err error) (retry, backpressure bool) {
var ue *copyUploadError
if !errors.As(err, &ue) {
return false, false
}
if ue.fromUploader {
return operation.ShouldReassignUpload(ue.err), operation.IsUploadBackpressure(ue.err)
}
overloaded := ue.status == http.StatusTooManyRequests || ue.status == http.StatusServiceUnavailable
refusedBeforeAppend := ue.status == http.StatusConflict && ue.outcome == util_http.WriteOutcomeRefusedBeforeAppend ||
ue.status == http.StatusUnauthorized && ue.outcome == util_http.WriteOutcomeExpiredJwtBeforeAppend
return ue.status == 0 || ue.status >= http.StatusInternalServerError || overloaded || refusedBeforeAppend, overloaded
}
// uploadCopiedChunk writes one destination chunk with upload to the volume
// assignResult names. When that volume fails the write in a way another one
// would not, it asks for a fresh assignment and writes the chunk there, up to
// copyChunkAssignAttempts volumes, as PutObject does for its chunks: a copy
// that met a full, lost or overloaded volume used to fail outright. Each
// failed write may have stored the needle before it failed, and no chunk will
// name it, so its fid is deleted; a failure before the write reached the
// volume, such as a source that could not be read, leaves nothing to delete.
// On success dstChunk names the volume the chunk landed on. size is the
// expected size for the assignment.
func (s3a *S3ApiServer) uploadCopiedChunk(dstChunk *filer_pb.FileChunk, assignResult *filer_pb.AssignVolumeResponse, dstPath string, size uint64, upload func(*filer_pb.AssignVolumeResponse) error) error {
backpressureReassigned := false
for attempt := 1; ; attempt++ {
err := upload(assignResult)
if err == nil {
return s3a.setChunkFileId(dstChunk, assignResult)
}
var ue *copyUploadError
if !errors.As(err, &ue) {
// nothing reached the volume, a failed source read for one
return err
}
deleteFailedCopyChunk(assignResult, s3a.lookupVolumeJwt)
retry, backpressure := reassignable(err)
if !retry || attempt == copyChunkAssignAttempts || backpressure && backpressureReassigned {
return err
}
backpressureReassigned = backpressureReassigned || backpressure
glog.V(1).Infof("copy to %s: chunk %s failed, assigning another volume (attempt %d/%d): %v", dstPath, assignResult.FileId, attempt+1, copyChunkAssignAttempts, err)
next, assignErr := s3a.assignNewVolume(dstPath, size)
if assignErr != nil {
return fmt.Errorf("reassign volume after %w: %w", err, assignErr)
}
assignResult = next
}
}
// copyCleanupTimeout bounds each delete of a failed copy chunk, its answer
// included, so a holder that stalls cannot hold up the copy's next volume.
var copyCleanupTimeout = 10 * time.Second
// deleteFailedCopyChunk best-effort removes the needle a failed copy write may
// have stored from each holder of its assignment, as PutObject drops a failed
// chunk; a failed delete leaves it unreferenced. The write token may have
// expired by then, so a holder that refuses it gets one delete under a token
// from lookupJwt.
func deleteFailedCopyChunk(assignResult *filer_pb.AssignVolumeResponse, lookupJwt func(context.Context, string) security.EncodedJwt) {
jwt := assignResult.Auth
hosts := []string{assignResult.GetLocation().GetUrl()}
for _, replica := range assignResult.GetReplicas() {
if url := replica.GetUrl(); url != "" && url != hosts[0] {
hosts = append(hosts, url)
}
}
for _, host := range hosts {
if host == "" {
continue
}
deleteUrl := fmt.Sprintf("http://%s/%s?type=replicate&%s=%s", host, assignResult.FileId, operation.ReplicateSourceParam, operation.ReplicateSourceClient)
status, body, err := deleteCopyChunkFrom(deleteUrl, jwt)
if status == http.StatusUnauthorized {
ctx, cancel := context.WithTimeout(context.Background(), copyCleanupTimeout)
token := lookupJwt(ctx, assignResult.FileId)
cancel()
if token != "" {
jwt = string(token)
status, body, err = deleteCopyChunkFrom(deleteUrl, jwt)
}
}
if err != nil {
// a read cut off after the answer began still has its status
glog.V(1).Infof("copy cleanup: delete failed chunk %s from %s: status %d: %s: %v", assignResult.FileId, host, status, body, err)
continue
}
switch status {
case http.StatusNotFound, http.StatusNoContent, http.StatusAccepted, http.StatusOK:
default:
glog.V(1).Infof("copy cleanup: delete failed chunk %s from %s: status %d: %s", assignResult.FileId, host, status, body)
}
}
}
// deleteCopyChunkFrom sends one delete and reads the start of its answer, for
// the log, within copyCleanupTimeout.
func deleteCopyChunkFrom(url, jwt string) (status int, body []byte, err error) {
ctx, cancel := context.WithTimeout(context.Background(), copyCleanupTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, url, nil)
if err != nil {
return 0, nil, err
}
if jwt != "" {
req.Header.Set("Authorization", security.BearerPrefix+jwt)
}
resp, err := util_http.GetGlobalHttpClient().Do(req)
if err != nil {
return 0, nil, err
}
defer util_http.CloseResponse(resp)
body, err = io.ReadAll(io.LimitReader(resp.Body, 4096))
return resp.StatusCode, body, err
}