Files
seaweedfs/weed/operation/upload_chunked.go
T
9ffb5fe185 filer, s3, filer.sync: one digest per cluster, set by the filer's -digest and followed by its clients (#12913)
* util, filer: choose the digest at filer startup with -digest

NewMd5 and NewSha1 returned SHA-256 cut to size whenever the process ran
under GODEBUG=fips140=only, so the kind of digest a cluster stores followed
each process's own environment. They now follow a digest mode set once at
startup: util.SetDigest("md5"|"sha256"), or "" to keep following
fips140.Enforced(). The default is unchanged.

weed filer -digest, weed server -filer.digest and weed mini -filer.digest
set it; fips140=only refuses md5 at startup. The leveldb2/leveldb3
directory-key marker follows the mode, as do the places that compare a
NewMd5 digest with Content-MD5 or pass it on as one: S3 PutObject, filer
HTTP uploads, the Content-MD5 the filer returns, and the uploader's
Content-MD5 to volume servers. Places that verify Content-MD5 with a real
MD5 (volume servers, S3 request bodies and archive uploads) keep keying on
fips140.Enforced(), since they can check it whenever MD5 is available.

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

* filer, command: report the filer's digest and make its clients use it

GetFilerConfigurationResponse carries the filer's digest mode in a new
field 16, digest. weed s3, mount, webdav, sftp, iam and filer.copy adopt
it before they serve or write, so a gateway started with a different
GODEBUG writes the same kind of ETag and chunk digest as the rest of the
cluster. A process under fips140=only refuses a filer that reports md5. A
filer that reports no digest predates the field; the client then keeps
its own mode and logs a warning.

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

* filer.sync, s3 sink: keep digests within one kind

filer.sync copies entry digests and ETags as they are, so syncing a filer
with digest sha256 into one with md5 left SHA-256 ETags in the md5
cluster. It now reads both filers' digests and refuses to start when they
differ, with a warning when either filer does not report one.

The S3 sink sent the entry digest as Content-MD5 unless its own process
ran under fips140=only. From a sha256 source into a target that checks
Content-MD5 every single-part upload failed with BadDigest and the backup
retried it forever. It now asks the source filer for its digest once and
forwards the entry digest only when that is md5.

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

* filer.meta.backup, filer.backup, filer.replicate: keep digests within one kind

filer.meta.backup opened its backup store in its own digest mode, so a copy
of a sha256 filer made by a process outside fips140=only got MD5 directory
keys and could not be opened as that filer's store. It now adopts the source
filer's digest before the store opens.

filer.backup and filer.replicate with a filer sink copied entry digests into
the target filer without comparing digests, as filer.sync did before. Both
now refuse, and exit, when the source and target filers report different
digests. replication.CheckDigestsMatch is the shared check; filer.sync uses
it too.

weed server and weed mini apply -filer.digest before they start the master
and volume server, so every part of the process hashes with one digest.

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

* filer, filer.sync: refuse a peer filer with another digest; exit on mismatch

Filers peering through the meta aggregator now compare digests. A peer with
a store of its own would replay entries holding the other kind of digest
into this filer's store, so its changes are refused and the reason logged
on every reconnect. A fresh filer bootstrapping from such a peer refuses the
copy, so a new filer whose digest differs from the existing filers' exits at
startup. A peer on the same store writes into it directly, and refusing its
stream would only starve this filer's subscribers, so that mismatch is
logged as an error and the stream kept.

filer.sync exits with status 1 when the two filers use different digests,
as filer.backup and filer.replicate do: it is a configuration error a
restart cannot fix.

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

* filer: -digest help says a store keeps the digest it was created with

The help text said existing data keeps the digest it was written with,
which reads as if the flag could be changed on a store with data. Stores
that hash keys stop finding existing entries under another digest, so the
text now says to set it when the store is created, and that switching means
copying the metadata into a new store with fs.meta.save and fs.meta.load.

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

* filer, s3, replication, admin, iceberg: address review of the digest checks

- A filer checks its peers' digests on every start, not only at the fresh-store
  bootstrap: the store signature is written when the store opens, so a fresh
  filer refused at bootstrap restarted as an initialized store and served
  without its peers' files.
- Under digest sha256 with MD5 available (not fips140=only), a client's
  Content-MD5 is checked against a separate real MD5 of the body, in S3 object,
  part and directory-marker uploads and in filer HTTP uploads. It goes
  unchecked only when no MD5 can be computed.
- filer.backup and filer.replicate exit only on a DigestMismatchError; a filer
  that cannot be reached is retried, so a backup started before its target is
  up resumes once the target answers.
- The admin file browser and Iceberg compaction write chunks into a filer they
  do not follow at process level. They read that filer's digest and pass it to
  the chunk upload (ChunkedUploadOption.Digest), so their content and chunk
  digests match the filer's.

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

* filer, s3 sink: retire digest-refused peers; no Content-MD5 for an unknown digest

- A peer refused for its digest counts as unreachable: the check now runs
  before notePeerReachable and its error wraps errPeerUnreachable, so the
  subscribe loop retires the peer from the low watermarks after the usual
  grace instead of keeping its zero watermark, which held every aggregated
  subscriber at the settled horizon.
- When the source filer's digest cannot be read, the S3 sink no longer sends
  the entry digest as Content-MD5: it may be a SHA-256 digest the target
  would reject.
- TestCheckPeerDigest skips the cases that need MD5 locally under
  GODEBUG=fips140=only.

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

* iceberg, util: tests for the per-filer digest

The Iceberg tests' fake filer serves GetFilerConfiguration, which uploads now
call to read the target filer's digest; it reports none, as a filer that
predates the setting does. TestNewContentMd5 computes a real MD5, so it skips
under GODEBUG=fips140=only.

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

* filer: bound each startup peer digest read with a timeout

CheckPeerDigests read each peer's configuration with the caller's context,
which at startup has no deadline, so a peer that accepted the connection but
never answered held the filer's startup. Each read now has its own
peerDigestReadTimeout (10s, inside the one-minute announce cap), after which
the peer is logged and skipped like an unreachable one.

setDigestForTest restores the previous digest setting instead of the default.

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

* util, s3, filer: one-shot digests for data held in memory

Md5For hashes with md5.Sum or sha256.Sum256 instead of writing into a
hash.Hash, and the Content-MD5 checks of S3 directory markers and of filer
uploads saved inside the filer use BodyMd5Of on the bytes they already hold.
Streaming uploads keep their io.TeeReader.

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

* filer: hash Content-MD5 on the upload's digest hash, not on its body

teeContentMd5 wrapped the request body in a TeeReader before
uploadRequestToChunks. CodeQL's go/reflected-xss query follows the body
from r.Body through the chunk upload to upload_content.go's
w.Write(prepared.data), which it resolves to the response-writer
wrappers in s3vectors, s3tables, webdav and server/common.go. Those
flows exist on master from other sources (extract, tagging, the
multipart POST); the wrapped body put them through lines this PR
changed, so CodeQL reported six of them as new.

newUploadHash now builds the digest hash that uploadReaderToChunks and
the inline-append paths already tee the body into, and adds the
separate MD5 there; uploadBodyMd5 reads it back for the check. The body
reaches uploadRequestToChunks as on master. Behaviour is unchanged:
under digest sha256 with MD5 available, Content-MD5 is checked against
the body's MD5, including empty and inline appends.

Checked with CodeQL 2.27.6 (go-queries 1.6.16, ReflectedXss.ql) on this
tree: no flow of the nine reflected-XSS results passes a changed line.

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

* replication: keep the ReadFilerSignature name and return the digest with it

Renaming it to ReadFilerSignatureAndDigest left its other callers with an
undefined function. Keep the name and add the digest to what it returns.

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

* util: keep HashToInt32 off the digest mode

HashToInt32 names things that processes derive on their own, such as a
mount's local socket path and MQ partition key hashes. weed mount adopts
a -digest=sha256 filer's digest before it names its socket, while
weed shell mount.configure keeps md5 and dialed a different socket.
Follow GODEBUG only, as before the digest setting.

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

* filer.meta.backup: wait for the source filer's digest instead of exiting

A backup with a saved offset used to start its stream loop and retry
until the source filer answered. Reading the digest first made it exit
when started before the filer. Retry the read; exit only when the
digest is refused.

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-11-24 20:17:26 -08:00

478 lines
17 KiB
Go

package operation
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"hash"
"io"
"net/http"
"sort"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// ErrTruncatedBody tags a source read that ended before the expected bytes
// arrived, so callers can tell a truncated input (client abort, reverse-proxy
// timeout) apart from a volume-server upload fault.
var ErrTruncatedBody = errors.New("truncated request body")
// ChunkedUploadResult contains the result of a chunked upload
type ChunkedUploadResult struct {
FileChunks []*filer_pb.FileChunk
Md5Hash hash.Hash
TotalSize int64
SmallContent []byte // For files smaller than threshold
}
// ChunkedUploadOption contains options for chunked uploads
type ChunkedUploadOption struct {
ChunkSize int32
SmallFileLimit int64
Collection string
Replication string
DataCenter string
SaveSmallInline bool
Jwt security.EncodedJwt
MimeType string
Cipher bool // encrypt data on volume servers
AssignFunc func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error)
UploadFunc func(ctx context.Context, data []byte, option *UploadOption) (*UploadResult, error) // Optional: for testing
LookupJwtFunc func(ctx context.Context, fileId string) security.EncodedJwt // Optional: renews the volume JWT for a cleanup delete
// Digest names the target filer's digest, so the content and chunk
// digests match what that filer holds; empty uses this process's mode.
Digest string
}
var chunkBufferPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
// UploadReaderInChunks reads from reader and uploads in chunks to volume servers
// This prevents OOM by processing the stream in fixed-size chunks
// Returns file chunks, MD5 hash, total size, and any small content stored inline
func UploadReaderInChunks(ctx context.Context, reader io.Reader, opt *ChunkedUploadOption) (*ChunkedUploadResult, error) {
return uploadReaderInChunks(ctx, reader, opt, prepareUploadData)
}
func uploadReaderInChunks(ctx context.Context, reader io.Reader, opt *ChunkedUploadOption, prepare func([]byte, *UploadOption) (*preparedUpload, error)) (*ChunkedUploadResult, error) {
md5Hash := util.NewMd5For(opt.Digest)
var partReader = io.TeeReader(reader, md5Hash)
var fileChunks []*filer_pb.FileChunk
var fileChunksLock sync.Mutex
var uploadErr error
var uploadErrLock sync.Mutex
var chunkOffset int64 = 0
var wg sync.WaitGroup
const bytesBufferCounter = 4
bytesBufferLimitChan := make(chan struct{}, bytesBufferCounter)
// objectFailed reports whether another chunk has already doomed the upload,
// so an in-flight chunk stops spending its retry budget on bytes nobody
// will reference.
objectFailed := func() bool {
uploadErrLock.Lock()
defer uploadErrLock.Unlock()
return uploadErr != nil
}
uploadLoop:
for {
// Throttle buffer usage
bytesBufferLimitChan <- struct{}{}
// Check for errors from parallel uploads
uploadErrLock.Lock()
if uploadErr != nil {
<-bytesBufferLimitChan
uploadErrLock.Unlock()
break
}
uploadErrLock.Unlock()
// Check for context cancellation
select {
case <-ctx.Done():
<-bytesBufferLimitChan
uploadErrLock.Lock()
if uploadErr == nil {
uploadErr = ctx.Err()
}
uploadErrLock.Unlock()
break uploadLoop
default:
}
// Get buffer from pool
bytesBuffer := chunkBufferPool.Get().(*bytes.Buffer)
limitedReader := io.LimitReader(partReader, int64(opt.ChunkSize))
bytesBuffer.Reset()
// Read one chunk
dataSize, err := bytesBuffer.ReadFrom(limitedReader)
if err != nil {
// Attach offset + bytes-read to distinguish client disconnect
// before any data (offset=0,got=0) from mid-stream truncation.
// A bare io.ErrUnexpectedEOF is not actionable on its own (see #9149).
wrapped := fmt.Errorf("read chunk at offset %d (got %d bytes): %w", chunkOffset, dataSize, err)
if errors.Is(err, io.ErrUnexpectedEOF) {
wrapped = fmt.Errorf("%w: %w", ErrTruncatedBody, wrapped)
}
glog.V(2).Infof("UploadReaderInChunks: %v", wrapped)
chunkBufferPool.Put(bytesBuffer)
<-bytesBufferLimitChan
uploadErrLock.Lock()
if uploadErr == nil {
uploadErr = wrapped
}
uploadErrLock.Unlock()
break
}
// If no data was read, we've reached EOF
// Only break if we've already read some data (chunkOffset > 0) or if this is truly EOF
if dataSize == 0 {
if chunkOffset == 0 {
// Empty objects are valid for S3/HTTP uploads (e.g. zero-byte files).
// Keep this at verbose level to avoid warning noise in normal operation.
glog.V(4).Infof("UploadReaderInChunks: received 0 bytes on first read - creating empty file")
}
chunkBufferPool.Put(bytesBuffer)
<-bytesBufferLimitChan
// If we've already read some chunks, this is normal EOF
// If we haven't read anything yet (chunkOffset == 0), this could be an empty file
// which is valid (e.g., touch command creates 0-byte files)
break
}
// For small files at offset 0, store inline instead of uploading
if chunkOffset == 0 && opt.SaveSmallInline && dataSize < opt.SmallFileLimit {
smallContent := make([]byte, dataSize)
n, readErr := io.ReadFull(bytesBuffer, smallContent)
chunkBufferPool.Put(bytesBuffer)
<-bytesBufferLimitChan
if readErr != nil {
return nil, fmt.Errorf("failed to read small content: read %d of %d bytes: %w", n, dataSize, readErr)
}
return &ChunkedUploadResult{
FileChunks: nil,
Md5Hash: md5Hash,
TotalSize: dataSize,
SmallContent: smallContent,
}, nil
}
// Upload chunk in parallel goroutine
wg.Add(1)
go func(offset int64, buf *bytes.Buffer, size int64) {
defer func() {
chunkBufferPool.Put(buf)
<-bytesBufferLimitChan
wg.Done()
}()
// Hash and prepare only this bounded chunk before minting its volume JWT.
chunkMd5 := util.Md5For(opt.Digest, buf.Bytes())
chunkMd5B64 := base64.StdEncoding.EncodeToString(chunkMd5[:])
var prepared *preparedUpload
if opt.UploadFunc == nil {
var prepareErr error
prepared, prepareErr = prepare(buf.Bytes(), chunkUploadOption(opt))
if prepareErr != nil {
uploadErrLock.Lock()
if uploadErr == nil {
uploadErr = fmt.Errorf("prepare chunk: %w", prepareErr)
}
uploadErrLock.Unlock()
return
}
}
// Assign volume for this chunk
_, assignResult, assignErr := opt.AssignFunc(ctx, 1, uint64(size))
if assignErr != nil {
uploadErrLock.Lock()
if uploadErr == nil {
uploadErr = fmt.Errorf("assign volume: %w", assignErr)
}
uploadErrLock.Unlock()
return
}
// Use per-assignment JWT if present, otherwise fall back to the original JWT
// This is critical for secured clusters where each volume assignment has its own JWT
jwt := opt.Jwt
if assignResult.Auth != "" {
jwt = assignResult.Auth
}
var uploadResult *UploadResult
var uploadResultErr error
// A target that fills up, loses its replica peer, or goes away fails
// every attempt against the same fid, so ask for a fresh assignment and
// retry there rather than losing the whole object to one bad volume.
for attempt := 1; ; attempt++ {
uploadResult, uploadResultErr = uploadChunk(ctx, assignResult, buf.Bytes(), prepared, jwt, chunkMd5B64, opt)
if uploadResultErr == nil {
break
}
// The volume server commits the needle before replicating, so a
// failed write can still leave a copy behind. No chunk will name
// this fid whether we retry or give up here, and an unreferenced
// needle is not garbage vacuum can find, so drop it either way.
deleteChunkFromHolders(chunkHolders(assignResult), assignResult.Fid, jwt, opt)
if attempt == chunkAssignAttempts || !ShouldReassignUpload(uploadResultErr) || objectFailed() {
break
}
glog.V(2).Infof("re-assigning chunk at offset %d after attempt %d/%d: %v", offset, attempt, chunkAssignAttempts, uploadResultErr)
_, assignResult, assignErr = opt.AssignFunc(ctx, 1, uint64(size))
if assignErr != nil {
uploadResultErr = fmt.Errorf("reassign volume after %w: %w", uploadResultErr, assignErr)
break
}
jwt = opt.Jwt
if assignResult.Auth != "" {
jwt = assignResult.Auth
}
}
if uploadResultErr != nil {
uploadErrLock.Lock()
if uploadErr == nil {
uploadErr = fmt.Errorf("upload chunk: %w", uploadResultErr)
}
uploadErrLock.Unlock()
return
}
// Create chunk entry
// Set ModifiedTsNs to current time (nanoseconds) to track when upload completed
// This is critical for multipart uploads where the same part may be uploaded multiple times
// The part with the latest ModifiedTsNs is selected as the authoritative version
fid, _ := filer_pb.ToFileIdObject(assignResult.Fid)
chunk := &filer_pb.FileChunk{
FileId: assignResult.Fid,
Offset: offset,
Size: uint64(uploadResult.Size),
ModifiedTsNs: time.Now().UnixNano(),
ETag: uploadResult.ContentMd5,
Fid: fid,
CipherKey: uploadResult.CipherKey,
IsCompressed: uploadResult.Gzip > 0,
}
fileChunksLock.Lock()
fileChunks = append(fileChunks, chunk)
fileChunksLock.Unlock()
}(chunkOffset, bytesBuffer, dataSize)
// Update offset for next chunk
chunkOffset += dataSize
// If this was a partial chunk, we're done
if dataSize < int64(opt.ChunkSize) {
break
}
}
// Wait for all uploads to complete
wg.Wait()
// Sort chunks by offset (do this even if there's an error, for cleanup purposes)
sort.Slice(fileChunks, func(i, j int) bool {
return fileChunks[i].Offset < fileChunks[j].Offset
})
// Check for errors - return partial results for cleanup
if uploadErr != nil {
glog.Errorf("chunked upload failed: %v (returning %d partial chunks for cleanup)", uploadErr, len(fileChunks))
// IMPORTANT: Return partial results even on error so caller can cleanup orphaned chunks
return &ChunkedUploadResult{
FileChunks: fileChunks,
Md5Hash: md5Hash,
TotalSize: chunkOffset,
SmallContent: nil,
}, uploadErr
}
return &ChunkedUploadResult{
FileChunks: fileChunks,
Md5Hash: md5Hash,
TotalSize: chunkOffset,
SmallContent: nil,
}, nil
}
// chunkAssignAttempts bounds how many volumes one chunk may be offered to
// before the upload gives up.
const chunkAssignAttempts = 3
// uploadChunk writes one chunk to its assigned volume. It fans out to every
// holder, except for cipher: per-call encryption would give each replica
// different bytes, so keep its relay path.
func uploadChunk(ctx context.Context, assignResult *AssignResult, data []byte, prepared *preparedUpload, jwt security.EncodedJwt, md5b64 string, opt *ChunkedUploadOption) (*UploadResult, error) {
holders := chunkHolders(assignResult)
if opt.UploadFunc == nil && !opt.Cipher && len(holders) > 1 {
return uploadChunkToHolders(ctx, holders, assignResult.Fid, prepared, jwt, md5b64, assignResult.Fsync, opt)
}
uploadOption := chunkUploadOption(opt)
uploadOption.UploadUrl = fmt.Sprintf("http://%s/%s", assignResult.Url, assignResult.Fid)
uploadOption.Jwt = jwt
uploadOption.Md5 = md5b64
// One upload call per assignment: the caller retries everything a
// same-URL retry would, and a different volume is the better second try.
// This bounds retriedUploadData only — doUploadData still reissues once
// on a connection reset, with a rewound body, which is a transport
// stutter rather than a fresh attempt at the volume. The fan-out path
// keeps its retries, where absorbing a blip locally beats cancelling
// every holder and re-uploading the chunk.
uploadOption.MaxAttempts = 1
if assignResult.Fsync {
uploadOption.UploadUrl += "?fsync=true"
}
// Use mock upload function if provided (for testing), otherwise use real uploader
if opt.UploadFunc != nil {
return opt.UploadFunc(ctx, data, uploadOption)
}
uploader, err := NewUploader()
if err != nil {
return nil, fmt.Errorf("create uploader: %w", err)
}
return uploader.retriedUploadData(ctx, prepared, uploadOption)
}
// chunkUploadOption holds the settings that shape a chunk's bytes, shared by
// its preparation and every upload of it.
func chunkUploadOption(opt *ChunkedUploadOption) *UploadOption {
return &UploadOption{Cipher: opt.Cipher, MimeType: opt.MimeType, Digest: opt.Digest}
}
// chunkHolders returns the assigned volume plus its replica holders.
func chunkHolders(assignResult *AssignResult) []string {
hosts := []string{assignResult.Url}
for _, replica := range assignResult.Replicas {
if replica.Url != "" && replica.Url != assignResult.Url {
hosts = append(hosts, replica.Url)
}
}
return hosts
}
// uploadChunkToHolders writes the chunk to every holder concurrently (each with
// type=replicate). On the first failure it cancels the remaining uploads and
// deletes any copies that already landed, so a partial fan-out leaves no
// orphaned needle the caller cannot see.
func uploadChunkToHolders(ctx context.Context, hosts []string, fid string, prepared *preparedUpload, jwt security.EncodedJwt, md5b64 string, fsync bool, opt *ChunkedUploadOption) (*UploadResult, error) {
uploader, err := NewUploader()
if err != nil {
return nil, fmt.Errorf("create uploader: %w", err)
}
glog.V(4).Infof("replica fan-out: writing chunk %s to %d holders %v", fid, len(hosts), hosts)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
type outcome struct {
host string
result *UploadResult
err error
}
outcomes := make(chan outcome, len(hosts))
for _, host := range hosts {
go func(host string) {
uploadUrl := fmt.Sprintf("http://%s/%s?type=replicate", host, fid)
if fsync {
uploadUrl += "&fsync=true"
}
uploadOption := chunkUploadOption(opt)
uploadOption.UploadUrl = uploadUrl
uploadOption.Jwt = jwt
uploadOption.Md5 = md5b64
r, e := uploader.retriedUploadData(ctx, prepared, uploadOption)
outcomes <- outcome{host, r, e}
}(host)
}
var first *UploadResult
var firstErr error
var succeeded []string
for range hosts {
o := <-outcomes
if o.err != nil {
// Once one holder fails the rest are cancelled, so errors arrive in
// no fixed order. Prefer one the caller can act on, or the choice of
// which host to report — and whether to retry elsewhere — turns on
// goroutine scheduling.
if firstErr == nil {
firstErr = o.err
cancel()
} else if !ShouldReassignUpload(firstErr) && ShouldReassignUpload(o.err) {
firstErr = o.err
}
} else {
succeeded = append(succeeded, o.host)
if first == nil {
first = o.result
}
}
}
if firstErr != nil {
// A failed fan-out records no chunk, so roll back the copies that landed
// before the cancel rather than leaking them as orphans.
deleteChunkFromHolders(succeeded, fid, jwt, opt)
return nil, firstErr
}
return first, nil
}
// cleanupJwtLookupTimeout bounds a cleanup-token renewal, covering the wait
// for a master plus the lookup RPC, so a master outage cannot stall the
// rollback of a failed fan-out.
const cleanupJwtLookupTimeout = 10 * time.Second
// deleteChunkFromHolders best-effort removes a needle from each holder it landed
// on, using type=replicate so the volume drops only its local copy. A failed
// delete falls back to vacuum reclaiming the orphan.
func deleteChunkFromHolders(hosts []string, fid string, jwt security.EncodedJwt, opt *ChunkedUploadOption) {
// An unresponsive holder can stall the upload past the write JWT's expiry,
// so renew the token whenever a holder rejects the delete as unauthorized.
// Each holder's delete is retried at most once, and a slow holder that
// outlives the renewed token can still trigger another renewal.
deleteJwt := jwt
for _, host := range hosts {
deleteUrl := fmt.Sprintf("http://%s/%s?type=replicate", host, fid)
body, status, err := util_http.DeleteProxied(deleteUrl, string(deleteJwt))
if status == http.StatusUnauthorized && opt.LookupJwtFunc != nil {
lookupCtx, cancel := context.WithTimeout(context.Background(), cleanupJwtLookupTimeout)
token := opt.LookupJwtFunc(lookupCtx, fid)
cancel()
if token != "" {
deleteJwt = token
body, status, err = util_http.DeleteProxied(deleteUrl, string(deleteJwt))
}
}
if err != nil {
glog.Warningf("replica fan-out cleanup: delete %s from %s: %v", fid, host, err)
continue
}
switch status {
case http.StatusNotFound, http.StatusNoContent, http.StatusAccepted, http.StatusOK:
default:
glog.Warningf("replica fan-out cleanup: delete %s from %s: status %d: %s", fid, host, status, body)
}
}
}