From 8ffce492fd14dcd455f9672174a2e435b971eeaa Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Sun, 22 Nov 2026 00:59:11 -0800 Subject: [PATCH] s3: time each stage of an object write (#12883) * s3: time each stage of an object write SeaweedFS_s3_request_seconds times the whole handler, so a slow PUT tail cannot be split into client upload time and server time. putToFiler now records SeaweedFS_s3_put_stage_seconds{operation,stage} per write: body_read (blocked on the request body), assign (volume assigns), chunk_upload (upload time apart from body reads: waiting on chunk uploads), and metadata (from the uploaded chunks to the committed entry). operation is PutObject or UploadPart; no per-bucket or per-object labels. Co-Authored-By: Claude Opus 5.5 * grafana: chart the S3 PUT stage p99 Co-Authored-By: Claude Opus 5.5 * s3: count body reads made before putToFiler in body_read mimeDetect reads the first bytes, and a POST upload parses the whole form, before putToFiler starts, so a slow client showed little body_read time. track now times every read of the request body, body_read reports the request's total, and chunk_upload subtracts only the reads made during the upload. Co-Authored-By: Claude Opus 5.5 * s3: observe body_read once per request An archive upload writes one object per member, and every write reported the same request-wide body read time. The first write to finish now reports it; the other stages stay per write. Co-Authored-By: Claude Opus 5.5 * s3: name the non-read upload stage storage The chunked upload runs volume assigns inside the chunk upload goroutines, so its time apart from body reads covers assigns and chunk uploads, and the uploads themselves cannot be timed from outside UploadReaderInChunks. Call that stage storage; assign stays the summed assign time within it. Co-Authored-By: Claude Opus 5.5 * s3: record a zero body_read for writes without a body timeBodyReads attached no timer to bodyless requests, so a zero-byte PUT or an UploadPartCopy recorded every stage but body_read. Co-Authored-By: Claude Opus 5.5 * s3: observe body_read after the handler so it covers every write An archive request writes several objects from one body. Observing body_read at the first write's record left out the reads of the later members. record now only marks the request, and track observes the request-wide total once the handler returns. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- other/metrics/grafana_seaweedfs.json | 96 ++++++++++++++++ weed/s3api/s3api_object_handlers_put.go | 4 +- weed/s3api/stats.go | 111 ++++++++++++++++++ weed/s3api/stats_test.go | 144 ++++++++++++++++++++++++ weed/stats/metrics.go | 9 ++ 5 files changed, 363 insertions(+), 1 deletion(-) diff --git a/other/metrics/grafana_seaweedfs.json b/other/metrics/grafana_seaweedfs.json index 32ccd70719..85a4f9fed7 100644 --- a/other/metrics/grafana_seaweedfs.json +++ b/other/metrics/grafana_seaweedfs.json @@ -9157,6 +9157,102 @@ } ], "pluginVersion": "10.3.1" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "title": "S3 PUT Stage Duration p99", + "description": "Time an object write (PutObject, UploadPart) spends waiting on the request body, volume assigns, chunk uploads apart from body reads, and the metadata commit after the upload.", + "type": "timeseries", + "id": 268, + "gridPos": { + "h": 8, + "w": 24, + "x": 0, + "y": 49 + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "drawStyle": "line", + "fillOpacity": 10, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 4, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "never", + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "mappings": [], + "unit": "s", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "legend": { + "calcs": [ + "lastNotNull", + "max" + ], + "displayMode": "table", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "code", + "expr": "histogram_quantile(0.99, sum(rate(SeaweedFS_s3_put_stage_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, operation, stage))", + "range": true, + "refId": "A", + "legendFormat": "{{operation}} {{stage}}" + } + ], + "pluginVersion": "10.3.1" } ] }, diff --git a/weed/s3api/s3api_object_handlers_put.go b/weed/s3api/s3api_object_handlers_put.go index a833a422b4..3a2b8ff61f 100644 --- a/weed/s3api/s3api_object_handlers_put.go +++ b/weed/s3api/s3api_object_handlers_put.go @@ -598,6 +598,8 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader if !s3_constants.IsValidBucketName(bucket) || (object != "" && !s3_constants.IsValidObjectKey(object)) { return "", s3err.ErrInvalidRequest, SSEResponseMetadata{} } + stages := newPutStages(r) + defer stages.record() tagSet, headerCode := validatePutHeaders(r) if headerCode != s3err.ErrNone { @@ -764,7 +766,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader // Upload with auto-chunking // Use context.Background() to ensure chunk uploads complete even if HTTP request is cancelled // This prevents partial uploads and data corruption - chunkResult, err := operation.UploadReaderInChunks(context.Background(), dataReader, &operation.ChunkedUploadOption{ + chunkResult, err := stages.upload(context.Background(), dataReader, &operation.ChunkedUploadOption{ ChunkSize: chunkSize, SmallFileLimit: smallFileLimit, Collection: collection, diff --git a/weed/s3api/stats.go b/weed/s3api/stats.go index 95d20b703e..05ccd4a634 100644 --- a/weed/s3api/stats.go +++ b/weed/s3api/stats.go @@ -1,10 +1,15 @@ package s3api import ( + "context" + "io" "net/http" "strconv" + "sync/atomic" "time" + "github.com/seaweedfs/seaweedfs/weed/operation" + "github.com/seaweedfs/seaweedfs/weed/util/version" "github.com/seaweedfs/seaweedfs/weed/glog" @@ -30,9 +35,11 @@ func track(f http.HandlerFunc, action string) http.HandlerFunc { // entry can report the requester even though auth records it on a // request copy this middleware never sees. r = s3_constants.EnsureIdentityHolder(r) + r = timeBodyReads(r) start := time.Now() f(recorder, r) elapsed := time.Since(start) + observeBodyRead(r) if glog.V(2) { requester := s3_constants.GetIdentityNameFromContext(r) if requester == "" { @@ -70,3 +77,107 @@ func BucketTrafficSent(bytesTransferred int64, r *http.Request) { stats_collect.RecordBucketActiveTime(bucket) stats_collect.S3BucketTrafficSentBytesCounter.WithLabelValues(bucket).Add(float64(bytesTransferred)) } + +// putStages times one object write's stages for S3PutStageHistogram. +type putStages struct { + r *http.Request + operation string + readDuring time.Duration + assign atomic.Int64 + uploading time.Duration + uploaded time.Time +} + +func newPutStages(r *http.Request) *putStages { + op := "PutObject" + if isMultipartPartRequest(r) { + op = "UploadPart" + } + return &putStages{r: r, operation: op} +} + +// upload runs UploadReaderInChunks, timing volume assigns and the body reads it waits on. +func (p *putStages) upload(ctx context.Context, reader io.Reader, opt *operation.ChunkedUploadOption) (*operation.ChunkedUploadResult, error) { + if assign := opt.AssignFunc; assign != nil { + opt.AssignFunc = func(ctx context.Context, count int, expectedDataSize uint64) (*operation.VolumeAssignRequest, *operation.AssignResult, error) { + start := time.Now() + defer func() { p.assign.Add(int64(time.Since(start))) }() + return assign(ctx, count, expectedDataSize) + } + } + readBefore := bodyReadTime(p.r) + start := time.Now() + result, err := operation.UploadReaderInChunks(ctx, reader, opt) + p.uploading = time.Since(start) + p.readDuring = bodyReadTime(p.r) - readBefore + if err == nil { + p.uploaded = time.Now() + } + return result, err +} + +// record observes the stages reached, metadata only after a successful upload, +// and leaves body_read to track so it covers every write of the request. +func (p *putStages) record() { + if p.uploading == 0 { + return + } + if reads, ok := p.r.Context().Value(bodyReadTimeKey{}).(*bodyReads); ok { + reads.operation.CompareAndSwap(nil, &p.operation) + } + observe := func(stage string, d time.Duration) { + stats_collect.S3PutStageHistogram.WithLabelValues(p.operation, stage).Observe(d.Seconds()) + } + observe("assign", time.Duration(p.assign.Load())) + observe("storage", max(p.uploading-p.readDuring, 0)) + if !p.uploaded.IsZero() { + observe("metadata", time.Since(p.uploaded)) + } +} + +type bodyReadTimeKey struct{} + +type bodyReads struct { + elapsed atomic.Int64 + operation atomic.Pointer[string] +} + +// timeBodyReads makes r count the time its body reads block, for bodyReadTime. +func timeBodyReads(r *http.Request) *http.Request { + reads := new(bodyReads) + r = r.WithContext(context.WithValue(r.Context(), bodyReadTimeKey{}, reads)) + if r.Body != nil && r.Body != http.NoBody { + r.Body = &timedBody{ReadCloser: r.Body, reads: reads} + } + return r +} + +func bodyReadTime(r *http.Request) time.Duration { + if reads, ok := r.Context().Value(bodyReadTimeKey{}).(*bodyReads); ok { + return time.Duration(reads.elapsed.Load()) + } + return 0 +} + +// observeBodyRead observes body_read once for a request that reached an upload. +func observeBodyRead(r *http.Request) { + reads, ok := r.Context().Value(bodyReadTimeKey{}).(*bodyReads) + if !ok { + return + } + if op := reads.operation.Load(); op != nil { + stats_collect.S3PutStageHistogram.WithLabelValues(*op, "body_read").Observe(time.Duration(reads.elapsed.Load()).Seconds()) + } +} + +type timedBody struct { + io.ReadCloser + reads *bodyReads +} + +func (t *timedBody) Read(b []byte) (int, error) { + start := time.Now() + n, err := t.ReadCloser.Read(b) + t.reads.elapsed.Add(int64(time.Since(start))) + return n, err +} diff --git a/weed/s3api/stats_test.go b/weed/s3api/stats_test.go index 63d019b906..7b651b4863 100644 --- a/weed/s3api/stats_test.go +++ b/weed/s3api/stats_test.go @@ -1,12 +1,22 @@ package s3api import ( + "bytes" + "context" + "errors" + "io" "net/http" "net/http/httptest" "testing" + "time" + "github.com/prometheus/client_golang/prometheus" + dto "github.com/prometheus/client_model/go" + "github.com/seaweedfs/seaweedfs/weed/operation" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + stats_collect "github.com/seaweedfs/seaweedfs/weed/stats" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // TestTrackAuditFallbackForDirectWriteHeader covers the regression behind @@ -49,3 +59,137 @@ func TestTrackAuditSkipsFallbackWhenHandlerEmits(t *testing.T) { "flag must be set after handler PostLog") } } + +type slowReader struct { + io.Reader + delay time.Duration +} + +func (s slowReader) Read(b []byte) (int, error) { + time.Sleep(s.delay) + return s.Reader.Read(b) +} + +func putStageSamples(t *testing.T, operation, stage string) (uint64, float64) { + t.Helper() + var m dto.Metric + require.NoError(t, stats_collect.S3PutStageHistogram.WithLabelValues(operation, stage).(prometheus.Histogram).Write(&m)) + return m.GetHistogram().GetSampleCount(), m.GetHistogram().GetSampleSum() +} + +func stagedUploadOption(assignDelay time.Duration, uploadErr error) *operation.ChunkedUploadOption { + return &operation.ChunkedUploadOption{ + ChunkSize: 4, + SmallFileLimit: 0, + AssignFunc: func(ctx context.Context, count int, expectedDataSize uint64) (*operation.VolumeAssignRequest, *operation.AssignResult, error) { + time.Sleep(assignDelay) + return nil, &operation.AssignResult{Fid: "3,01637037d6", Url: "127.0.0.1:1", Count: 1}, nil + }, + UploadFunc: func(ctx context.Context, data []byte, option *operation.UploadOption) (*operation.UploadResult, error) { + if uploadErr != nil { + return nil, uploadErr + } + return &operation.UploadResult{Size: uint32(len(data))}, nil + }, + } +} + +func TestPutStagesRecordEachStage(t *testing.T) { + body := slowReader{Reader: bytes.NewReader([]byte("12345678")), delay: 10 * time.Millisecond} + r := withMultipartPart(httptest.NewRequest(http.MethodPut, "/bucket/object?partNumber=1&uploadId=u", body), uploadFilerClient{}) + before := map[string]uint64{} + sums := map[string]float64{} + for _, stage := range []string{"body_read", "assign", "storage", "metadata"} { + before[stage], sums[stage] = putStageSamples(t, "UploadPart", stage) + } + + r = timeBodyReads(r) + stages := newPutStages(r) + result, err := stages.upload(context.Background(), r.Body, stagedUploadOption(20*time.Millisecond, nil)) + require.NoError(t, err) + require.Len(t, result.FileChunks, 2) + time.Sleep(5 * time.Millisecond) + stages.record() + observeBodyRead(r) + + for stage, atLeast := range map[string]time.Duration{"body_read": 20 * time.Millisecond, "assign": 40 * time.Millisecond, "storage": 5 * time.Millisecond, "metadata": 5 * time.Millisecond} { + count, sum := putStageSamples(t, "UploadPart", stage) + assert.Equal(t, before[stage]+1, count, stage) + assert.GreaterOrEqual(t, sum-sums[stage], atLeast.Seconds(), stage) + } +} + +func TestPutStagesSkipMetadataAfterFailedUpload(t *testing.T) { + r := timeBodyReads(httptest.NewRequest(http.MethodPut, "/bucket/object", bytes.NewReader([]byte("1234")))) + bodyBefore, _ := putStageSamples(t, "PutObject", "body_read") + metadataBefore, _ := putStageSamples(t, "PutObject", "metadata") + + stages := newPutStages(r) + _, err := stages.upload(context.Background(), r.Body, stagedUploadOption(0, errors.New("volume down"))) + require.Error(t, err) + stages.record() + observeBodyRead(r) + + bodyAfter, _ := putStageSamples(t, "PutObject", "body_read") + metadataAfter, _ := putStageSamples(t, "PutObject", "metadata") + assert.Equal(t, bodyBefore+1, bodyAfter) + assert.Equal(t, metadataBefore, metadataAfter) +} + +func TestTrackTimesBodyReadsBeforeTheWrite(t *testing.T) { + var readBeforeWrite time.Duration + handler := func(w http.ResponseWriter, r *http.Request) { + prefix := make([]byte, 2) + _, _ = io.ReadFull(r.Body, prefix) + readBeforeWrite = bodyReadTime(r) + w.WriteHeader(http.StatusOK) + } + body := slowReader{Reader: bytes.NewReader([]byte("1234")), delay: 10 * time.Millisecond} + track(handler, "PUT")(httptest.NewRecorder(), httptest.NewRequest(http.MethodPut, "/bucket/object", body)) + assert.GreaterOrEqual(t, readBeforeWrite, 10*time.Millisecond) +} + +func TestPutStagesRecordBodyReadOncePerRequest(t *testing.T) { + before, sumBefore := putStageSamples(t, "PutObject", "body_read") + uploadsBefore, _ := putStageSamples(t, "PutObject", "storage") + handler := func(w http.ResponseWriter, r *http.Request) { + for i := 0; i < 3; i++ { + stages := newPutStages(r) + _, err := stages.upload(context.Background(), io.LimitReader(r.Body, 4), stagedUploadOption(0, nil)) + require.NoError(t, err) + stages.record() + } + w.WriteHeader(http.StatusOK) + } + body := slowReader{Reader: bytes.NewReader([]byte("123456789012")), delay: 10 * time.Millisecond} + track(handler, "PUT")(httptest.NewRecorder(), httptest.NewRequest(http.MethodPut, "/bucket/archive.zip", body)) + after, sumAfter := putStageSamples(t, "PutObject", "body_read") + uploadsAfter, _ := putStageSamples(t, "PutObject", "storage") + assert.Equal(t, before+1, after) + assert.GreaterOrEqual(t, sumAfter-sumBefore, (30 * time.Millisecond).Seconds()) + assert.Equal(t, uploadsBefore+3, uploadsAfter) +} + +func TestPutStagesRecordBodyReadForEmptyBody(t *testing.T) { + r := timeBodyReads(httptest.NewRequest(http.MethodPut, "/bucket/empty", http.NoBody)) + assert.Equal(t, http.NoBody, r.Body) + before, _ := putStageSamples(t, "PutObject", "body_read") + stages := newPutStages(r) + _, err := stages.upload(context.Background(), r.Body, stagedUploadOption(0, nil)) + require.NoError(t, err) + stages.record() + observeBodyRead(r) + after, _ := putStageSamples(t, "PutObject", "body_read") + assert.Equal(t, before+1, after) +} + +func TestPutStagesRecordNothingBeforeUpload(t *testing.T) { + before, _ := putStageSamples(t, "PutObject", "body_read") + handler := func(w http.ResponseWriter, r *http.Request) { + newPutStages(r).record() + w.WriteHeader(http.StatusBadRequest) + } + track(handler, "PUT")(httptest.NewRecorder(), httptest.NewRequest(http.MethodPut, "/bucket/object", bytes.NewReader([]byte("1234")))) + after, _ := putStageSamples(t, "PutObject", "body_read") + assert.Equal(t, before, after) +} diff --git a/weed/stats/metrics.go b/weed/stats/metrics.go index d01c62e71a..264c7cfacc 100644 --- a/weed/stats/metrics.go +++ b/weed/stats/metrics.go @@ -790,6 +790,14 @@ var ( Help: "Bucketed histogram of s3 time to first byte request processing time.", Buckets: prometheus.ExponentialBuckets(0.001, 2, 27), }, []string{"type", "bucket"}) + S3PutStageHistogram = prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Namespace: Namespace, + Subsystem: subsystemS3, + Name: "put_stage_seconds", + Help: "Bucketed histogram of the time one s3 object write spends in each stage: body_read waits on the request body, assign on volume assigns, storage on volume assigns and chunk uploads (the chunked upload apart from body reads), metadata from the uploaded chunks to the committed entry.", + Buckets: prometheus.ExponentialBuckets(0.0001, 2, 24), + }, []string{"operation", "stage"}) S3InFlightRequestsGauge = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: Namespace, @@ -1198,6 +1206,7 @@ func init() { Gather.MustRegister(S3InFlightUploadBytesGauge) Gather.MustRegister(S3InFlightUploadCountGauge) Gather.MustRegister(S3TimeToFirstByteHistogram) + Gather.MustRegister(S3PutStageHistogram) Gather.MustRegister(S3BucketTrafficReceivedBytesCounter) Gather.MustRegister(S3BucketTrafficSentBytesCounter) Gather.MustRegister(S3DeletedObjectsCounter)