mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-09-08 15:41:15 +02:00
* filer: store TUS sub-chunks through the regular chunk writer A TUS sub-chunk was written with one assigned file id, retried up to three times against that same id, and abandoned on failure: an attempt that had landed on some replicas left a needle no session record and no entry ever references, unreclaimable by vacuum. dataToChunkWithSSE, which the regular write path uses per chunk, assigns a fresh file id per attempt and hands back the file ids of failed attempts, which are now freed the way the regular write path frees them. * filer: retry a chunk write on a fresh volume when the server 5xxs The filer's chunk writer assigns a fresh file id per attempt but only retried transient network errors, so a volume filling up and turning read-only mid-write failed the whole request even though the very next assignment would have landed elsewhere. Every other write client already routes this through ShouldReassignUpload; the filer's own write path now does the same, for regular uploads and TUS sub-chunks alike. * filer: export the chunk deletion queue The filer test harness in weed/server builds filer.Filer as a struct literal, so any code path reaching DeleteChunks dereferenced a nil queue. Exported like the neighboring DeletionRetryQueue so the harness can arm it. * filer: complete a TUS upload whose chunk records overlap A PATCH retried while its predecessor was still storing a sub-chunk - a proxy timeout with an immediate retry is enough - records the same range twice. HEAD computes Upload-Offset as the covered watermark and reported the upload fully received, but completion demanded exactly adjacent records and failed every attempt: the client concluded success from offset == length, no entry was created, and the session eventually expired, turning the entire upload into deleted needles for the vacuum to chew through. Completion now validates gapless coverage with the same watermark HEAD uses. A record extending coverage joins the entry - the read path resolves partial overlaps by ModifiedTsNs, and the raced copies carry identical bytes - while a fully covered duplicate is freed once the entry lands. * filer: allow one mutating TUS request per session at a time Nothing stopped two PATCHes from writing the same range concurrently: both loaded the same offset, both passed the conflict check, and both recorded their sub-chunks. A client whose request timed out in a proxy retries immediately while the server side is still storing the buffered sub-chunk, which is exactly that race. A session now accepts one PATCH or DELETE at a time, the way tusd locks uploads; a concurrent one is refused with 423 Locked, which TUS clients retry, and HEAD keeps answering so progress polling is unaffected. The chunk state is loaded under the claim, so a retried PATCH sees every record its predecessor left and conflicts cleanly instead of duplicating data. * test: cover a TUS PATCH raced by its own retry Stalls a PATCH mid-body over a raw connection, retries the same range while it is in flight, and expects the retry refused with 423 Locked; the upload then resumes from the reported offset and the final content must be intact. * filer: never free a TUS duplicate the entry still references Coverage is computed from ranges, so a record fully covered by another is treated as a duplicate no matter which needle it names. A malformed record naming a file id the entry keeps would have had that needle freed right after the entry landed - the corruption this change set exists to stop. The duplicates are now freed in one batch, skipping any file id the entry references; their records go with the session directory. * test: bound the raw TUS connection reads http.ReadResponse on the stalled PATCH's connection blocked until the whole go test timeout if the filer never answered. * filer: free the needles of chunk write attempts a retry replaced A volume server stores the needle locally and only then fans out to the replicas, so a replication failure 5xxs with the data already written. Each attempt assigns its own file id, so once a later attempt lands elsewhere nothing references the earlier ones: the caller only sees the chunk that succeeded, and the failed ids were dropped. They are now freed the way the caller frees them when the whole write fails. Retrying on a 5xx makes this reachable on every read-only or full volume, which is exactly the condition that filled the reporter's volumes.
271 lines
8.7 KiB
Go
271 lines
8.7 KiB
Go
package weed_server
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/md5"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"hash"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"sync"
|
|
"time"
|
|
|
|
"slices"
|
|
|
|
"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"
|
|
"github.com/seaweedfs/seaweedfs/weed/stats"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
)
|
|
|
|
var bufPool = sync.Pool{
|
|
New: func() interface{} {
|
|
return new(bytes.Buffer)
|
|
},
|
|
}
|
|
|
|
func (fs *FilerServer) uploadRequestToChunks(ctx context.Context, w http.ResponseWriter, r *http.Request, reader io.Reader, chunkSize int32, fileName, contentType string, contentLength int64, so *operation.StorageOption) (fileChunks []*filer_pb.FileChunk, md5Hash hash.Hash, chunkOffset int64, uploadErr error, smallContent []byte) {
|
|
query := r.URL.Query()
|
|
|
|
isAppend := isAppend(r)
|
|
if query.Has("offset") {
|
|
offset := query.Get("offset")
|
|
offsetInt, err := strconv.ParseInt(offset, 10, 64)
|
|
if err != nil || offsetInt < 0 {
|
|
err = fmt.Errorf("invalid 'offset': '%s'", offset)
|
|
return nil, nil, 0, err, nil
|
|
}
|
|
if isAppend && offsetInt > 0 {
|
|
err = fmt.Errorf("cannot set offset when op=append")
|
|
return nil, nil, 0, err, nil
|
|
}
|
|
chunkOffset = offsetInt
|
|
}
|
|
|
|
return fs.uploadReaderToChunks(ctx, r, reader, chunkOffset, chunkSize, fileName, contentType, isAppend, so)
|
|
}
|
|
|
|
func (fs *FilerServer) uploadReaderToChunks(ctx context.Context, r *http.Request, reader io.Reader, startOffset int64, chunkSize int32, fileName, contentType string, isAppend bool, so *operation.StorageOption) (fileChunks []*filer_pb.FileChunk, md5Hash hash.Hash, chunkOffset int64, uploadErr error, smallContent []byte) {
|
|
|
|
md5Hash = md5.New()
|
|
chunkOffset = startOffset
|
|
var partReader = io.NopCloser(io.TeeReader(reader, md5Hash))
|
|
|
|
var wg sync.WaitGroup
|
|
var bytesBufferCounter int64 = 4
|
|
bytesBufferLimitChan := make(chan struct{}, bytesBufferCounter)
|
|
var fileChunksLock sync.Mutex
|
|
var uploadErrLock sync.Mutex
|
|
for {
|
|
|
|
// need to throttle used byte buffer
|
|
bytesBufferLimitChan <- struct{}{}
|
|
|
|
// As long as there is an error in the upload of one chunk, it can be terminated early
|
|
// uploadErr may be modified in other go routines, lock is needed to avoid race condition
|
|
uploadErrLock.Lock()
|
|
if uploadErr != nil {
|
|
<-bytesBufferLimitChan
|
|
uploadErrLock.Unlock()
|
|
break
|
|
}
|
|
uploadErrLock.Unlock()
|
|
|
|
bytesBuffer := bufPool.Get().(*bytes.Buffer)
|
|
|
|
limitedReader := io.LimitReader(partReader, int64(chunkSize))
|
|
|
|
bytesBuffer.Reset()
|
|
|
|
dataSize, err := bytesBuffer.ReadFrom(limitedReader)
|
|
|
|
// data, err := io.ReadAll(limitedReader)
|
|
if err != nil || dataSize == 0 {
|
|
bufPool.Put(bytesBuffer)
|
|
<-bytesBufferLimitChan
|
|
if err != nil {
|
|
uploadErrLock.Lock()
|
|
if uploadErr == nil {
|
|
uploadErr = err
|
|
}
|
|
uploadErrLock.Unlock()
|
|
}
|
|
break
|
|
}
|
|
if chunkOffset == 0 && !isAppend {
|
|
if dataSize < fs.option.SaveToFilerLimit {
|
|
chunkOffset += dataSize
|
|
smallContent = make([]byte, dataSize)
|
|
bytesBuffer.Read(smallContent)
|
|
bufPool.Put(bytesBuffer)
|
|
<-bytesBufferLimitChan
|
|
stats.FilerHandlerCounter.WithLabelValues(stats.ContentSaveToFiler).Inc()
|
|
break
|
|
}
|
|
} else {
|
|
stats.FilerHandlerCounter.WithLabelValues(stats.AutoChunk).Inc()
|
|
}
|
|
|
|
wg.Add(1)
|
|
go func(offset int64, buf *bytes.Buffer) {
|
|
defer func() {
|
|
bufPool.Put(buf)
|
|
<-bytesBufferLimitChan
|
|
wg.Done()
|
|
}()
|
|
|
|
chunks, toChunkErr := fs.dataToChunkWithSSE(ctx, r, fileName, contentType, buf.Bytes(), offset, so)
|
|
if toChunkErr != nil {
|
|
uploadErrLock.Lock()
|
|
if uploadErr == nil {
|
|
uploadErr = toChunkErr
|
|
}
|
|
uploadErrLock.Unlock()
|
|
}
|
|
if chunks != nil {
|
|
fileChunksLock.Lock()
|
|
for _, chunk := range chunks {
|
|
fileChunks = append(fileChunks, chunk)
|
|
}
|
|
fileChunksLock.Unlock()
|
|
}
|
|
}(chunkOffset, bytesBuffer)
|
|
|
|
// reset variables for the next chunk
|
|
glog.V(4).Infof("uploadReaderToChunks read chunk at offset %d, size %d", chunkOffset, dataSize)
|
|
chunkOffset = chunkOffset + dataSize
|
|
|
|
// if last chunk was not at full chunk size, but already exhausted the reader
|
|
if dataSize < int64(chunkSize) {
|
|
break
|
|
}
|
|
}
|
|
|
|
wg.Wait()
|
|
|
|
if uploadErr != nil {
|
|
glog.V(0).InfofCtx(ctx, "upload file %s error: %v", fileName, uploadErr)
|
|
for _, chunk := range fileChunks {
|
|
glog.V(4).InfofCtx(ctx, "purging failed uploaded %s chunk %s [%d,%d)", fileName, chunk.FileId, chunk.Offset, chunk.Offset+int64(chunk.Size))
|
|
}
|
|
fs.filer.DeleteUncommittedChunks(ctx, fileChunks)
|
|
return nil, md5Hash, 0, uploadErr, nil
|
|
}
|
|
slices.SortFunc(fileChunks, func(a, b *filer_pb.FileChunk) int {
|
|
return int(a.Offset - b.Offset)
|
|
})
|
|
return fileChunks, md5Hash, chunkOffset, nil, smallContent
|
|
}
|
|
|
|
func (fs *FilerServer) doUpload(ctx context.Context, urlLocation string, limitedReader io.Reader, fileName string, contentType string, pairMap map[string]string, auth security.EncodedJwt, contentMd5 string) (*operation.UploadResult, error, []byte) {
|
|
|
|
stats.FilerHandlerCounter.WithLabelValues(stats.ChunkUpload).Inc()
|
|
start := time.Now()
|
|
defer func() {
|
|
stats.FilerRequestHistogram.WithLabelValues(stats.ChunkUpload).Observe(time.Since(start).Seconds())
|
|
}()
|
|
|
|
uploadOption := &operation.UploadOption{
|
|
UploadUrl: urlLocation,
|
|
Filename: fileName,
|
|
Cipher: fs.option.Cipher,
|
|
IsInputCompressed: false,
|
|
MimeType: contentType,
|
|
PairMap: pairMap,
|
|
Jwt: auth,
|
|
Md5: contentMd5,
|
|
}
|
|
|
|
uploader, err := operation.NewUploader()
|
|
if err != nil {
|
|
return nil, err, []byte{}
|
|
}
|
|
|
|
// Use a context that ignores cancellation from the request context
|
|
uploadCtx := context.WithoutCancel(ctx)
|
|
|
|
uploadResult, err, data := uploader.Upload(uploadCtx, limitedReader, uploadOption)
|
|
if uploadResult != nil && uploadResult.RetryCount > 0 {
|
|
stats.FilerHandlerCounter.WithLabelValues(stats.ChunkUploadRetry).Add(float64(uploadResult.RetryCount))
|
|
}
|
|
return uploadResult, err, data
|
|
}
|
|
|
|
func (fs *FilerServer) dataToChunkWithSSE(ctx context.Context, r *http.Request, fileName, contentType string, data []byte, chunkOffset int64, so *operation.StorageOption) ([]*filer_pb.FileChunk, error) {
|
|
dataReader := util.NewBytesReader(data)
|
|
|
|
// retry to assign a different file id
|
|
var fileId, urlLocation string
|
|
var auth security.EncodedJwt
|
|
var uploadErr error
|
|
var uploadResult *operation.UploadResult
|
|
var failedFileChunks []*filer_pb.FileChunk
|
|
|
|
// Each attempt assigns anew, so also retry the errors a fresh volume dodges:
|
|
// a target gone read-only or full mid-write 5xxs until the master notices.
|
|
shouldRetry := func(err error) bool {
|
|
return util.IsTransientError(err) || operation.ShouldReassignUpload(err)
|
|
}
|
|
err := util.RetryOnError("filerDataToChunk", shouldRetry, func() error {
|
|
// assign one file id for one chunk
|
|
fileId, urlLocation, auth, uploadErr = fs.assignNewFileInfo(ctx, so, uint64(len(data)))
|
|
if uploadErr != nil {
|
|
glog.V(4).InfofCtx(ctx, "retry later due to assign error: %v", uploadErr)
|
|
stats.FilerHandlerCounter.WithLabelValues(stats.ChunkAssignRetry).Inc()
|
|
return uploadErr
|
|
}
|
|
chunkMd5 := md5.Sum(data)
|
|
chunkMd5B64 := base64.StdEncoding.EncodeToString(chunkMd5[:])
|
|
// upload the chunk to the volume server
|
|
uploadResult, uploadErr, _ = fs.doUpload(ctx, urlLocation, dataReader, fileName, contentType, nil, auth, chunkMd5B64)
|
|
if uploadErr != nil {
|
|
glog.V(4).InfofCtx(ctx, "retry later due to upload error: %v", uploadErr)
|
|
stats.FilerHandlerCounter.WithLabelValues(stats.ChunkDoUploadRetry).Inc()
|
|
fid, _ := filer_pb.ToFileIdObject(fileId)
|
|
fileChunk := filer_pb.FileChunk{
|
|
FileId: fileId,
|
|
Offset: chunkOffset,
|
|
Fid: fid,
|
|
}
|
|
failedFileChunks = append(failedFileChunks, &fileChunk)
|
|
return uploadErr
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
glog.ErrorfCtx(ctx, "upload error: %v", err)
|
|
return failedFileChunks, err
|
|
}
|
|
|
|
// A retry that lands elsewhere strands the earlier attempts: a volume server
|
|
// 5xxs after storing the needle locally when replication fails, and each
|
|
// attempt used its own file id, so nothing references them now.
|
|
if len(failedFileChunks) > 0 {
|
|
fs.filer.DeleteUncommittedChunks(ctx, failedFileChunks)
|
|
}
|
|
|
|
// if last chunk exhausted the reader exactly at the border
|
|
if uploadResult.Size == 0 {
|
|
return nil, nil
|
|
}
|
|
|
|
// Extract SSE metadata from request headers if available
|
|
var sseType filer_pb.SSEType = filer_pb.SSEType_NONE
|
|
var sseMetadata []byte
|
|
|
|
// Create chunk with SSE metadata if available
|
|
var chunk *filer_pb.FileChunk
|
|
if sseType != filer_pb.SSEType_NONE {
|
|
chunk = uploadResult.ToPbFileChunkWithSSE(fileId, chunkOffset, time.Now().UnixNano(), sseType, sseMetadata)
|
|
} else {
|
|
chunk = uploadResult.ToPbFileChunk(fileId, chunkOffset, time.Now().UnixNano())
|
|
}
|
|
|
|
return []*filer_pb.FileChunk{chunk}, nil
|
|
}
|