From 1e4739f97aa9020170bac9fcc41b32160565fa69 Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Fri, 27 Nov 2026 17:44:12 -0800 Subject: [PATCH] s3api: count object reads that fail after the status line is sent (#13073) * s3api: count object reads that fail after the status line is sent A GET whose body breaks after the 200/206 was committed is recorded by SeaweedFS_s3_request_total as a success and only shows up in the log. SeaweedFS_s3_read_aborted_total{bucket,cause} counts these reads on the volume-server, SSE and remote-mount stream paths, split into client_canceled, deadline_exceeded and read_error, and is dropped with the other per-bucket series when a bucket is deleted. Co-Authored-By: Claude Opus 5.5 * grafana: plot aborted S3 reads by bucket and cause Co-Authored-By: Claude Opus 5.5 * s3api: count aborted reads of inline objects and directory content Co-Authored-By: Claude Opus 5.5 * s3api: count gRPC deadline failures as deadline_exceeded aborted reads Co-Authored-By: Claude Opus 5.5 * s3api: count an aborted read as client_canceled only when its request was canceled A context.Canceled error under a live request context comes from an internal cancellation, such as a shared lookup canceled by another request, so it is recorded as read_error. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- other/metrics/grafana_seaweedfs.json | 96 ++++++++++++++++++++ weed/s3api/s3api_local_read_fallback_test.go | 77 ++++++++++++++++ weed/s3api/s3api_object_handlers.go | 7 ++ weed/s3api/stats.go | 27 ++++++ weed/s3api/stats_test.go | 31 +++++++ weed/stats/metrics.go | 10 ++ 6 files changed, 248 insertions(+) diff --git a/other/metrics/grafana_seaweedfs.json b/other/metrics/grafana_seaweedfs.json index 6f35148c7b..36e17344f8 100644 --- a/other/metrics/grafana_seaweedfs.json +++ b/other/metrics/grafana_seaweedfs.json @@ -10356,6 +10356,102 @@ } ], "pluginVersion": "10.3.1" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "title": "S3 Aborted Reads by Bucket", + "description": "Object reads that failed after the status line was sent: the request counter records them as successes, so they only show here.", + "type": "timeseries", + "id": 270, + "gridPos": { + "h": 8, + "w": 24, + "x": 0, + "y": 66 + }, + "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": "reqps", + "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": "sum by (bucket, cause) (rate(SeaweedFS_s3_read_aborted_total{cluster=~\"$cluster\", bucket=~\"$bucket\"}[$__rate_interval]))", + "range": true, + "refId": "A", + "legendFormat": "{{bucket}} {{cause}}" + } + ], + "pluginVersion": "10.3.1" } ] }, diff --git a/weed/s3api/s3api_local_read_fallback_test.go b/weed/s3api/s3api_local_read_fallback_test.go index 6294ca1c0c..9b604242a1 100644 --- a/weed/s3api/s3api_local_read_fallback_test.go +++ b/weed/s3api/s3api_local_read_fallback_test.go @@ -10,11 +10,14 @@ import ( "testing" "time" + "github.com/gorilla/mux" + "github.com/prometheus/client_golang/prometheus/testutil" "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/remote_storage" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + stats_collect "github.com/seaweedfs/seaweedfs/weed/stats" "github.com/seaweedfs/seaweedfs/weed/util/chunk_cache" "github.com/seaweedfs/seaweedfs/weed/wdclient" "github.com/stretchr/testify/assert" @@ -364,3 +367,77 @@ func TestStreamRangeToClientFinishesFromRemote(t *testing.T) { assert.Nil(t, client.gotLoc, "the client is gone; refetching from the remote is wasted work") }) } + +func TestS3ReadFailingAfterCommitCountsAbortedRead(t *testing.T) { + const bucket = "abortedreadbkt" + content := []byte("0123456789") + s3a := newLocalReadFallbackServer(t, startStreamThroughFiler(t, "faketest-abortedread", nil)) + cache := chunk_cache.NewChunkCacheInMemory(16) + cache.SetChunk("1,0123456789ab", content[:5]) + s3a.readerCache = filer.NewReaderCache(8, cache, s3a.filerClient.GetLookupFileIdFunction(), s3a.filerClient) + entry := &filer_pb.Entry{ + Name: "obj.bin", + Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(content))}, + Chunks: []*filer_pb.FileChunk{ + {FileId: "1,0123456789ab", Size: 5, Offset: 0, ModifiedTsNs: 1}, + {FileId: "2,0123456789cd", Size: 5, Offset: 5, ModifiedTsNs: 1}, + }, + } + aborted := func() float64 { + return testutil.ToFloat64(stats_collect.S3ReadAbortedCounter.WithLabelValues(bucket, readAbortedReadError)) + } + defer stats_collect.DeleteBucketMetrics(bucket) + before := aborted() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + r := httptest.NewRequest(http.MethodGet, "/"+bucket+"/obj.bin", nil).WithContext(ctx) + r = mux.SetURLVars(r, map[string]string{"bucket": bucket, "object": "obj.bin"}) + w := httptest.NewRecorder() + + err := s3a.streamFromVolumeServers(w, r, entry, "", bucket, "obj.bin", "") + + var streamErr *StreamError + require.True(t, errors.As(err, &streamErr) && streamErr.ResponseWritten, "a failure after the first chunk must leave the 200 committed: %v", err) + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, content[:5], w.Body.Bytes()) + assert.Equal(t, before+1, aborted(), "a read that dies after the status line must be counted") +} + +type failingResponseWriter struct { + *httptest.ResponseRecorder + err error +} + +func (f failingResponseWriter) Write(p []byte) (int, error) { return 0, f.err } + +func TestS3InlineReadFailingWriteCountsAbortedRead(t *testing.T) { + const bucket = "abortedinlinebkt" + content := []byte("0123456789") + s3a := newLocalReadFallbackServer(t, startStreamThroughFiler(t, "faketest-abortedinline", nil)) + entry := &filer_pb.Entry{ + Name: "obj.bin", + Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(content))}, + Content: content, + } + aborted := func() float64 { + return testutil.ToFloat64(stats_collect.S3ReadAbortedCounter.WithLabelValues(bucket, readAbortedReadError)) + } + defer stats_collect.DeleteBucketMetrics(bucket) + + for _, rangeHeader := range []string{"", "bytes=2-5"} { + before := aborted() + r := httptest.NewRequest(http.MethodGet, "/"+bucket+"/obj.bin", nil) + if rangeHeader != "" { + r.Header.Set("Range", rangeHeader) + } + r = mux.SetURLVars(r, map[string]string{"bucket": bucket, "object": "obj.bin"}) + w := failingResponseWriter{ResponseRecorder: httptest.NewRecorder(), err: errors.New("write: connection reset by peer")} + + err := s3a.streamFromVolumeServers(w, r, entry, "", bucket, "obj.bin", "") + + var streamErr *StreamError + require.True(t, errors.As(err, &streamErr) && streamErr.ResponseWritten, "range %q: %v", rangeHeader, err) + assert.Equal(t, before+1, aborted(), "range %q: a failed inline write must be counted", rangeHeader) + } +} diff --git a/weed/s3api/s3api_object_handlers.go b/weed/s3api/s3api_object_handlers.go index 3bdb38d229..71c1bbf15c 100644 --- a/weed/s3api/s3api_object_handlers.go +++ b/weed/s3api/s3api_object_handlers.go @@ -643,6 +643,7 @@ func (s3a *S3ApiServer) serveDirectoryContent(w http.ResponseWriter, r *http.Req w.WriteHeader(statusCode) if len(content) > 0 { if _, err := w.Write(content); err != nil { + BucketReadAborted(err, r) glog.Errorf("serveDirectoryContent: failed to write response: %v", err) } } @@ -1274,6 +1275,7 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R BucketTrafficSent(int64(written), r) } if err != nil { + BucketReadAborted(err, r) return newStreamErrorWithResponse(err) } return nil @@ -1286,6 +1288,7 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R BucketTrafficSent(int64(written), r) } if err != nil { + BucketReadAborted(err, r) return newStreamErrorWithResponse(err) } return nil @@ -1497,6 +1500,7 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R s3err.WriteErrorResponse(w, r, s3err.ErrInternalError) return newStreamErrorWithResponse(err) } + BucketReadAborted(err, r) switch { case streamCanceled(r.Context(), err): // Client disconnected mid-stream (e.g. Nginx upstream timeout, browser cancel) - expected @@ -1591,6 +1595,7 @@ func (s3a *S3ApiServer) serveObjectFromRemoteMount(w http.ResponseWriter, r *htt BucketTrafficSent(cw.written, r) } if copyErr != nil { + BucketReadAborted(copyErr, r) glog.V(2).Infof("streamFromVolumeServers: origin stream %s/%s ended after %d bytes: %v", bucket, object, cw.written, copyErr) return true, copyErr } @@ -1782,6 +1787,7 @@ func (s3a *S3ApiServer) streamFromVolumeServersWithSSE(w http.ResponseWriter, r // nothing written yet -- the caller writes the S3 error response return err } + BucketReadAborted(err, r) return newStreamErrorWithResponse(err) } body.Commit() @@ -1936,6 +1942,7 @@ func (s3a *S3ApiServer) streamFromVolumeServersWithSSE(w http.ResponseWriter, r // nothing written yet -- the caller writes the S3 error response return copyErr } + BucketReadAborted(copyErr, r) return newStreamErrorWithResponse(copyErr) } body.Commit() diff --git a/weed/s3api/stats.go b/weed/s3api/stats.go index 05ccd4a634..799007aaf2 100644 --- a/weed/s3api/stats.go +++ b/weed/s3api/stats.go @@ -2,6 +2,7 @@ package s3api import ( "context" + "errors" "io" "net/http" "strconv" @@ -16,6 +17,8 @@ import ( "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" stats_collect "github.com/seaweedfs/seaweedfs/weed/stats" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) func track(f http.HandlerFunc, action string) http.HandlerFunc { @@ -78,6 +81,30 @@ func BucketTrafficSent(bytesTransferred int64, r *http.Request) { stats_collect.S3BucketTrafficSentBytesCounter.WithLabelValues(bucket).Add(float64(bytesTransferred)) } +const ( + readAbortedClientCanceled = "client_canceled" + readAbortedDeadlineExceeded = "deadline_exceeded" + readAbortedReadError = "read_error" +) + +func readAbortedCause(ctx context.Context, err error) string { + switch { + case ctx.Err() == context.Canceled: + return readAbortedClientCanceled + case errors.Is(err, context.DeadlineExceeded), status.Code(err) == codes.DeadlineExceeded: + return readAbortedDeadlineExceeded + default: + return readAbortedReadError + } +} + +// BucketReadAborted counts a read whose status line was already sent, so the +// request counter records it as a success. +func BucketReadAborted(err error, r *http.Request) { + bucket, _ := s3_constants.GetBucketAndObject(r) + stats_collect.S3ReadAbortedCounter.WithLabelValues(bucket, readAbortedCause(r.Context(), err)).Inc() +} + // putStages times one object write's stages for S3PutStageHistogram. type putStages struct { r *http.Request diff --git a/weed/s3api/stats_test.go b/weed/s3api/stats_test.go index 1e0f892c1f..18b532d1b3 100644 --- a/weed/s3api/stats_test.go +++ b/weed/s3api/stats_test.go @@ -4,19 +4,24 @@ import ( "bytes" "context" "errors" + "fmt" "io" "net/http" "net/http/httptest" "testing" "time" + "github.com/gorilla/mux" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/testutil" 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" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // TestTrackAuditFallbackForDirectWriteHeader covers the regression behind @@ -193,3 +198,29 @@ func TestPutStagesRecordNothingBeforeUpload(t *testing.T) { after, _ := putStageSamples(t, "PutObject", "body_read") assert.Equal(t, before, after) } + +func TestBucketReadAbortedCountsByCause(t *testing.T) { + const bucket = "read-aborted-bkt" + newReq := func(ctx context.Context) *http.Request { + r := httptest.NewRequest(http.MethodGet, "/"+bucket+"/obj", nil).WithContext(ctx) + return mux.SetURLVars(r, map[string]string{"bucket": bucket, "object": "obj"}) + } + canceled, cancel := context.WithCancel(context.Background()) + cancel() + + BucketReadAborted(errors.New("write: broken pipe"), newReq(canceled)) + BucketReadAborted(context.Canceled, newReq(context.Background())) + BucketReadAborted(fmt.Errorf("read chunk: %w", context.DeadlineExceeded), newReq(context.Background())) + BucketReadAborted(fmt.Errorf("lookup: %w", status.Error(codes.DeadlineExceeded, "deadline")), newReq(context.Background())) + BucketReadAborted(io.ErrUnexpectedEOF, newReq(context.Background())) + + count := func(cause string) float64 { + return testutil.ToFloat64(stats_collect.S3ReadAbortedCounter.WithLabelValues(bucket, cause)) + } + assert.Equal(t, 1.0, count(readAbortedClientCanceled)) + assert.Equal(t, 2.0, count(readAbortedDeadlineExceeded)) + assert.Equal(t, 2.0, count(readAbortedReadError), "a cancellation under a live request context is not the client's") + + stats_collect.DeleteBucketMetrics(bucket) + assert.Zero(t, stats_collect.S3ReadAbortedCounter.DeletePartialMatch(prometheus.Labels{"bucket": bucket}), "bucket deletion must drop its aborted-read series") +} diff --git a/weed/stats/metrics.go b/weed/stats/metrics.go index 28cf89939d..7a5b29d0d0 100644 --- a/weed/stats/metrics.go +++ b/weed/stats/metrics.go @@ -773,6 +773,14 @@ var ( Help: "Counter of s3 requests.", }, []string{"type", "code", "bucket"}) + S3ReadAbortedCounter = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: Namespace, + Subsystem: subsystemS3, + Name: "read_aborted_total", + Help: "Counter of s3 object reads that failed after the response status was sent, by bucket and cause.", + }, []string{"bucket", "cause"}) + S3HandlerCounter = prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: Namespace, @@ -1209,6 +1217,7 @@ func init() { Gather.MustRegister(MasterVolumeCreationCounter) Gather.MustRegister(S3RequestCounter) + Gather.MustRegister(S3ReadAbortedCounter) Gather.MustRegister(S3HandlerCounter) Gather.MustRegister(S3RequestHistogram) Gather.MustRegister(S3InFlightRequestsGauge) @@ -1325,6 +1334,7 @@ func DeleteBucketMetrics(bucket string) { labels := prometheus.Labels{"bucket": bucket} c := S3RequestCounter.DeletePartialMatch(labels) + c += S3ReadAbortedCounter.DeletePartialMatch(labels) c += S3RequestHistogram.DeletePartialMatch(labels) c += S3TimeToFirstByteHistogram.DeletePartialMatch(labels) c += S3BucketTrafficReceivedBytesCounter.DeletePartialMatch(labels)