diff --git a/other/metrics/grafana_seaweedfs.json b/other/metrics/grafana_seaweedfs.json index ec559743eb..1b114ebc3b 100644 --- a/other/metrics/grafana_seaweedfs.json +++ b/other/metrics/grafana_seaweedfs.json @@ -7826,6 +7826,390 @@ } ], "pluginVersion": "10.3.1" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "title": "Filer gRPC QPS by method", + "description": "gRPC calls to the filer (mounts, S3 gateways, peers, shell), by method.", + "type": "timeseries", + "id": 271, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 103 + }, + "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 (method) (rate(SeaweedFS_filer_grpc_request_total{cluster=~\"$cluster\"}[$__rate_interval]))", + "range": true, + "refId": "A", + "legendFormat": "{{method}}" + } + ], + "pluginVersion": "10.3.1" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "title": "Filer gRPC Errors by method and code", + "description": "gRPC calls to the filer that did not end OK. NotFound is mostly lookups of names that do not exist.", + "type": "timeseries", + "id": 272, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 103 + }, + "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 (method, code) (rate(SeaweedFS_filer_grpc_request_total{code!=\"OK\", cluster=~\"$cluster\"}[$__rate_interval]))", + "range": true, + "refId": "A", + "legendFormat": "{{method}} {{code}}" + } + ], + "pluginVersion": "10.3.1" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "title": "Filer gRPC Duration p99 by method", + "description": "Subscriptions, health watches and client streams are counted but not timed.", + "type": "timeseries", + "id": 273, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 111 + }, + "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_filer_grpc_request_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, method))", + "range": true, + "refId": "A", + "legendFormat": "{{method}}" + } + ], + "pluginVersion": "10.3.1" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "title": "Filer gRPC Duration p50 by method", + "description": "Subscriptions, health watches and client streams are counted but not timed.", + "type": "timeseries", + "id": 274, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 111 + }, + "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.50, sum(rate(SeaweedFS_filer_grpc_request_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, method))", + "range": true, + "refId": "A", + "legendFormat": "{{method}}" + } + ], + "pluginVersion": "10.3.1" } ] }, diff --git a/weed/command/filer.go b/weed/command/filer.go index 1f252798f9..7afa369363 100644 --- a/weed/command/filer.go +++ b/weed/command/filer.go @@ -537,7 +537,8 @@ func (fo *FilerOptions) startFiler() { glog.Fatalf("failed to listen on grpc port %d: %v", grpcPort, err) } grpcTLSOption, grpcTLSReloadOption := security.LoadServerTLS(util.GetViper(), "grpc.filer") - grpcOptions := append([]grpc.ServerOption{grpcTLSOption, grpcTLSReloadOption}, fs.GrpcScopeServerOptions()...) + grpcOptions := append([]grpc.ServerOption{grpcTLSOption, grpcTLSReloadOption}, weed_server.FilerGrpcMetricsServerOptions()...) + grpcOptions = append(grpcOptions, fs.GrpcScopeServerOptions()...) grpcS := pb.NewGrpcServer(grpcOptions...) filer_pb.RegisterSeaweedFilerServer(grpcS, fs) diff --git a/weed/server/filer_grpc_metrics.go b/weed/server/filer_grpc_metrics.go new file mode 100644 index 0000000000..f15e365689 --- /dev/null +++ b/weed/server/filer_grpc_metrics.go @@ -0,0 +1,80 @@ +package weed_server + +import ( + "context" + "errors" + "strings" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/stats" +) + +// FilerGrpcMetricsServerOptions returns the gRPC server options that count the +// filer's gRPC calls and time them (SeaweedFS_filer_grpc_request_total and +// SeaweedFS_filer_grpc_request_seconds). The mounts and the S3 gateway work +// through this port: without it the filer's request metrics show its HTTP API +// and say nothing of a lookup, a create, a rename or a listing they send. +// +// The options go before the interceptors that may refuse a call, so a refused +// call is counted with its code. +func FilerGrpcMetricsServerOptions() []grpc.ServerOption { + return []grpc.ServerOption{ + grpc.ChainUnaryInterceptor(filerGrpcMetricsUnary), + grpc.ChainStreamInterceptor(filerGrpcMetricsStream), + } +} + +func filerGrpcMetricsUnary(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + start := time.Now() + resp, err := handler(ctx, req) + method := filerGrpcMethodLabel(info.FullMethod) + stats.FilerGrpcRequestCounter.WithLabelValues(method, filerGrpcCodeLabel(err)).Inc() + stats.FilerGrpcRequestHistogram.WithLabelValues(method).Observe(time.Since(start).Seconds()) + return resp, err +} + +// A stream is counted when it ends, and timed unless the client holds it open +// for as long as it runs: how long a subscription lasted says nothing about +// the filer, and would fill the top bucket. +func filerGrpcMetricsStream(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + start := time.Now() + err := handler(srv, ss) + method := filerGrpcMethodLabel(info.FullMethod) + stats.FilerGrpcRequestCounter.WithLabelValues(method, filerGrpcCodeLabel(err)).Inc() + if !info.IsClientStream && !strings.HasPrefix(method, "Subscribe") && method != "grpc.health.v1.Health/Watch" { + stats.FilerGrpcRequestHistogram.WithLabelValues(method).Observe(time.Since(start).Seconds()) + } + return err +} + +// filerGrpcMethodLabel names a call by its method for the filer's own +// service, "CreateEntry" for "/filer_pb.SeaweedFiler/CreateEntry", and by +// service and method for any other service on the port. +func filerGrpcMethodLabel(fullMethod string) string { + name := strings.TrimPrefix(fullMethod, "/") + if method, ok := strings.CutPrefix(name, "filer_pb.SeaweedFiler/"); ok { + return method + } + return name +} + +// filerGrpcCodeLabel is the gRPC status code a call ends with. A lookup of a +// name that does not exist returns filer_pb.ErrNotFound as it is, which +// carries no status and reaches the client as Unknown; it is labelled +// NotFound, so that the everyday miss stays apart from the errors nothing +// names. +func filerGrpcCodeLabel(err error) string { + if errors.Is(err, filer_pb.ErrNotFound) { + return codes.NotFound.String() + } + s, ok := status.FromError(err) + if !ok { + s = status.FromContextError(err) + } + return s.Code().String() +} diff --git a/weed/server/filer_grpc_metrics_test.go b/weed/server/filer_grpc_metrics_test.go new file mode 100644 index 0000000000..99dbc03062 --- /dev/null +++ b/weed/server/filer_grpc_metrics_test.go @@ -0,0 +1,168 @@ +package weed_server + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + + "github.com/prometheus/client_golang/prometheus/testutil" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/stats" +) + +func grpcRequests(method, code string) float64 { + return testutil.ToFloat64(stats.FilerGrpcRequestCounter.WithLabelValues(method, code)) +} + +// grpcTimed is how many calls of method the histogram has observed. +func grpcTimed(t *testing.T, method string) uint64 { + t.Helper() + families, err := stats.Gather.Gather() + if err != nil { + t.Fatalf("gather: %v", err) + } + for _, family := range families { + if family.GetName() != "SeaweedFS_filer_grpc_request_seconds" { + continue + } + for _, metric := range family.GetMetric() { + for _, label := range metric.GetLabel() { + if label.GetName() == "method" && label.GetValue() == method { + return metric.GetHistogram().GetSampleCount() + } + } + } + } + return 0 +} + +// A unary call is counted under its method and the status code it ends with, +// and timed, whether the handler answers or fails. +func TestFilerGrpcMetricsCountUnaryCallsByMethodAndCode(t *testing.T) { + info := &grpc.UnaryServerInfo{FullMethod: "/filer_pb.SeaweedFiler/MetricsTestUnary"} + ok0, aborted0, unknown0 := grpcRequests("MetricsTestUnary", "OK"), grpcRequests("MetricsTestUnary", "Aborted"), grpcRequests("MetricsTestUnary", "Unknown") + timed0 := grpcTimed(t, "MetricsTestUnary") + + resp, err := filerGrpcMetricsUnary(context.Background(), "req", info, func(ctx context.Context, req any) (any, error) { + return "resp", nil + }) + if resp != "resp" || err != nil { + t.Fatalf("the handler's answer did not come through: %v, %v", resp, err) + } + conflict := status.Error(codes.Aborted, "transaction conflict") + if _, err := filerGrpcMetricsUnary(context.Background(), "req", info, func(ctx context.Context, req any) (any, error) { + return nil, conflict + }); err != conflict { + t.Fatalf("the handler's error did not come through: %v", err) + } + // an error without a gRPC status is what the client sees as Unknown + filerGrpcMetricsUnary(context.Background(), "req", info, func(ctx context.Context, req any) (any, error) { + return nil, errors.New("plain") + }) + + if got := grpcRequests("MetricsTestUnary", "OK") - ok0; got != 1 { + t.Errorf("OK calls counted: %v, want 1", got) + } + if got := grpcRequests("MetricsTestUnary", "Aborted") - aborted0; got != 1 { + t.Errorf("Aborted calls counted: %v, want 1", got) + } + if got := grpcRequests("MetricsTestUnary", "Unknown") - unknown0; got != 1 { + t.Errorf("Unknown calls counted: %v, want 1", got) + } + if got := grpcTimed(t, "MetricsTestUnary") - timed0; got != 3 { + t.Errorf("calls timed: %d, want 3", got) + } +} + +// A stream is counted when it ends. A listing is timed; a subscription or a +// health watch, which the client holds open, and a client stream are not. +func TestFilerGrpcMetricsCountStreamsAndTimeTheFiniteOnes(t *testing.T) { + run := func(method string, clientStream bool, err error) { + fullMethod := "/filer_pb.SeaweedFiler/" + method + if strings.Contains(method, "/") { + fullMethod = "/" + method + } + info := &grpc.StreamServerInfo{FullMethod: fullMethod, IsServerStream: true, IsClientStream: clientStream} + if got := filerGrpcMetricsStream(nil, nil, info, func(srv any, stream grpc.ServerStream) error { return err }); got != err { + t.Fatalf("%s: the handler's error did not come through: %v", method, got) + } + } + tests := []struct { + method string + clientStream bool + err error + code string + timed uint64 + }{ + {"MetricsTestList", false, nil, "OK", 1}, + {"SubscribeMetricsTest", false, status.Error(codes.Canceled, "client left"), "Canceled", 0}, + {"MetricsTestBidi", true, nil, "OK", 0}, + {"grpc.health.v1.Health/Watch", false, status.Error(codes.Canceled, "client left"), "Canceled", 0}, + } + for _, tt := range tests { + counted0, timed0 := grpcRequests(tt.method, tt.code), grpcTimed(t, tt.method) + run(tt.method, tt.clientStream, tt.err) + if got := grpcRequests(tt.method, tt.code) - counted0; got != 1 { + t.Errorf("%s: %s streams counted: %v, want 1", tt.method, tt.code, got) + } + if got := grpcTimed(t, tt.method) - timed0; got != tt.timed { + t.Errorf("%s: streams timed: %d, want %d", tt.method, got, tt.timed) + } + } +} + +// A lookup that finds nothing returns filer_pb.ErrNotFound without a status: +// it is counted as NotFound, not with the errors that have no code. +func TestFilerGrpcMetricsCountAMissAsNotFound(t *testing.T) { + info := &grpc.UnaryServerInfo{FullMethod: "/filer_pb.SeaweedFiler/MetricsTestLookup"} + notFound0, unknown0 := grpcRequests("MetricsTestLookup", "NotFound"), grpcRequests("MetricsTestLookup", "Unknown") + for _, err := range []error{filer_pb.ErrNotFound, fmt.Errorf("lookup /a/b: %w", filer_pb.ErrNotFound)} { + if _, got := filerGrpcMetricsUnary(context.Background(), "req", info, func(ctx context.Context, req any) (any, error) { + return nil, err + }); got != err { + t.Fatalf("the handler's error did not come through: %v", got) + } + } + if got := grpcRequests("MetricsTestLookup", "NotFound") - notFound0; got != 2 { + t.Errorf("NotFound calls counted: %v, want 2", got) + } + if got := grpcRequests("MetricsTestLookup", "Unknown") - unknown0; got != 0 { + t.Errorf("Unknown calls counted: %v, want 0", got) + } +} + +// A handler that returns its context's error reaches the client as Canceled or +// DeadlineExceeded, and is counted so, wrapped or not. +func TestFilerGrpcMetricsCountContextErrorsAsTheClientSeesThem(t *testing.T) { + for err, want := range map[error]string{ + context.Canceled: "Canceled", + context.DeadlineExceeded: "DeadlineExceeded", + fmt.Errorf("batch: %w", context.Canceled): "Canceled", + fmt.Errorf("cache: %w", context.DeadlineExceeded): "DeadlineExceeded", + fmt.Errorf("op: %w", status.Error(codes.Aborted, "conflict")): "Aborted", + errors.New("plain"): "Unknown", + } { + if got := filerGrpcCodeLabel(err); got != want { + t.Errorf("filerGrpcCodeLabel(%v) = %q, want %q", err, got, want) + } + } +} + +func TestFilerGrpcMethodLabel(t *testing.T) { + for full, want := range map[string]string{ + "/filer_pb.SeaweedFiler/CreateEntry": "CreateEntry", + "/filer_pb.SeaweedFiler/ListEntries": "ListEntries", + "/iam_pb.SeaweedIdentityAccessManagement/GetUser": "iam_pb.SeaweedIdentityAccessManagement/GetUser", + "/grpc.health.v1.Health/Check": "grpc.health.v1.Health/Check", + } { + if got := filerGrpcMethodLabel(full); got != want { + t.Errorf("filerGrpcMethodLabel(%q) = %q, want %q", full, got, want) + } + } +} diff --git a/weed/stats/metrics.go b/weed/stats/metrics.go index 297ad0bcde..65c07783fd 100644 --- a/weed/stats/metrics.go +++ b/weed/stats/metrics.go @@ -226,6 +226,25 @@ var ( Buckets: prometheus.ExponentialBuckets(0.0001, 2, 24), }, []string{"type"}) + // The mounts and the S3 gateway reach the filer over gRPC; the request + // counter and histogram above see its HTTP API only. + FilerGrpcRequestCounter = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: Namespace, + Subsystem: subsystemFiler, + Name: "grpc_request_total", + Help: "Counter of filer gRPC requests, by method and gRPC status code.", + }, []string{"method", "code"}) + + FilerGrpcRequestHistogram = prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Namespace: Namespace, + Subsystem: subsystemFiler, + Name: "grpc_request_seconds", + Help: "Bucketed histogram of filer gRPC request processing time, by method.", + Buckets: prometheus.ExponentialBuckets(0.0001, 2, 24), + }, []string{"method"}) + FilerInFlightRequestsGauge = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: Namespace, @@ -1154,6 +1173,8 @@ func init() { Gather.MustRegister(FilerHandlerCounter) Gather.MustRegister(FilerRequestHistogram) Gather.MustRegister(FilerInFlightRequestsGauge) + Gather.MustRegister(FilerGrpcRequestCounter) + Gather.MustRegister(FilerGrpcRequestHistogram) Gather.MustRegister(FilerInFlightUploadBytesGauge) Gather.MustRegister(FilerInFlightUploadCountGauge) Gather.MustRegister(FilerStoreCounter)