From edc39da0b1690d3f5fab0a811b6e06f74d1e4b45 Mon Sep 17 00:00:00 2001 From: Benjamin Pracht Date: Wed, 18 Jan 2023 11:53:20 -0800 Subject: [PATCH] Add TwirpRequestStatusReporter twirp server hook to count requests (#1309) --- go.mod | 2 +- go.sum | 4 +- pkg/service/egress.go | 3 +- pkg/service/errors.go | 30 ++++++----- pkg/service/server.go | 3 +- pkg/service/twirp.go | 87 ++++++++++++++++++++++++++++++-- pkg/telemetry/prometheus/node.go | 16 +++++- 7 files changed, 120 insertions(+), 25 deletions(-) diff --git a/go.mod b/go.mod index 4585cbbe..224a7292 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,7 @@ require ( github.com/livekit/mageutil v0.0.0-20221221221243-f361fbe40290 github.com/livekit/mediatransportutil v0.0.0-20230111071722-904079e94a7c github.com/livekit/protocol v1.3.2 - github.com/livekit/psrpc v0.2.3 + github.com/livekit/psrpc v0.2.4-0.20230117222629-750daf611ec6 github.com/livekit/rtcscore-go v0.0.0-20220815072451-20ee10ae1995 github.com/mackerelio/go-osstat v0.2.3 github.com/magefile/mage v1.14.0 diff --git a/go.sum b/go.sum index 79105165..877e2719 100644 --- a/go.sum +++ b/go.sum @@ -235,8 +235,8 @@ github.com/livekit/mediatransportutil v0.0.0-20230111071722-904079e94a7c h1:wdzw github.com/livekit/mediatransportutil v0.0.0-20230111071722-904079e94a7c/go.mod h1:1Dlx20JPoIKGP45eo+yuj0HjeE25zmyeX/EWHiPCjFw= github.com/livekit/protocol v1.3.2 h1:3goGWbB5HFRb3tMjog8KP0nvZL1Fy6zut3W1psBzqE4= github.com/livekit/protocol v1.3.2/go.mod h1:gwCG03nKlHlC9hTjL4pXQpn783ALhmbyhq65UZxqbb8= -github.com/livekit/psrpc v0.2.3 h1:M8B/BdrrpRUj3Uj2MeOIDvJDFqiydoN2yeW4P0EF4ZQ= -github.com/livekit/psrpc v0.2.3/go.mod h1:+nJvbKx9DCZ6PSAsMHJPRAKjmRJ5WiyyhEmbKYqMKto= +github.com/livekit/psrpc v0.2.4-0.20230117222629-750daf611ec6 h1:rQ2AYPTFxFO8GTN+sT2I3ELbjMEpudgKvkH5sFta5a8= +github.com/livekit/psrpc v0.2.4-0.20230117222629-750daf611ec6/go.mod h1:+nJvbKx9DCZ6PSAsMHJPRAKjmRJ5WiyyhEmbKYqMKto= github.com/livekit/rtcscore-go v0.0.0-20220815072451-20ee10ae1995 h1:vOaY2qvfLihDyeZtnGGN1Law9wRrw8BMGCr1TygTvMw= github.com/livekit/rtcscore-go v0.0.0-20220815072451-20ee10ae1995/go.mod h1:116ych8UaEs9vfIE8n6iZCZ30iagUFTls0vRmC+Ix5U= github.com/mackerelio/go-osstat v0.2.3 h1:jAMXD5erlDE39kdX2CU7YwCGRcxIO33u/p8+Fhe5dJw= diff --git a/pkg/service/egress.go b/pkg/service/egress.go index d45128d7..c331d035 100644 --- a/pkg/service/egress.go +++ b/pkg/service/egress.go @@ -12,6 +12,7 @@ import ( "github.com/livekit/protocol/livekit" "github.com/livekit/protocol/logger" "github.com/livekit/protocol/utils" + "github.com/twitchtv/twirp" "github.com/livekit/livekit-server/pkg/telemetry" ) @@ -301,7 +302,7 @@ func (s *EgressService) StopEgress(ctx context.Context, req *livekit.StopEgressR } else { if info.Status != livekit.EgressStatus_EGRESS_STARTING && info.Status != livekit.EgressStatus_EGRESS_ACTIVE { - return nil, fmt.Errorf("egress with status %s cannot be stopped", info.Status.String()) + return nil, twirp.NewError(twirp.FailedPrecondition, fmt.Sprintf("egress with status %s cannot be stopped", info.Status.String())) } } diff --git a/pkg/service/errors.go b/pkg/service/errors.go index 44d80260..b856579d 100644 --- a/pkg/service/errors.go +++ b/pkg/service/errors.go @@ -1,19 +1,21 @@ package service -import "errors" +import ( + "github.com/livekit/psrpc" +) var ( - ErrEgressNotFound = errors.New("egress does not exist") - ErrEgressNotConnected = errors.New("egress not connected (redis required)") - ErrIdentityEmpty = errors.New("identity cannot be empty") - ErrIngressNotConnected = errors.New("ingress not connected (redis required)") - ErrIngressNotFound = errors.New("ingress does not exist") - ErrMetadataExceedsLimits = errors.New("metadata size exceeds limits") - ErrOperationFailed = errors.New("operation cannot be completed") - ErrParticipantNotFound = errors.New("participant does not exist") - ErrRoomNotFound = errors.New("requested room does not exist") - ErrRoomLockFailed = errors.New("could not lock room") - ErrRoomUnlockFailed = errors.New("could not unlock room, lock token does not match") - ErrTrackNotFound = errors.New("track is not found") - ErrWebHookMissingAPIKey = errors.New("api_key is required to use webhooks") + ErrEgressNotFound = psrpc.NewErrorf(psrpc.NotFound, "egress does not exist") + ErrEgressNotConnected = psrpc.NewErrorf(psrpc.Internal, "egress not connected (redis required)") + ErrIdentityEmpty = psrpc.NewErrorf(psrpc.InvalidArgument, "identity cannot be empty") + ErrIngressNotConnected = psrpc.NewErrorf(psrpc.Internal, "ingress not connected (redis required)") + ErrIngressNotFound = psrpc.NewErrorf(psrpc.NotFound, "ingress does not exist") + ErrMetadataExceedsLimits = psrpc.NewErrorf(psrpc.InvalidArgument, "metadata size exceeds limits") + ErrOperationFailed = psrpc.NewErrorf(psrpc.Internal, "operation cannot be completed") + ErrParticipantNotFound = psrpc.NewErrorf(psrpc.NotFound, "participant does not exist") + ErrRoomNotFound = psrpc.NewErrorf(psrpc.NotFound, "requested room does not exist") + ErrRoomLockFailed = psrpc.NewErrorf(psrpc.Internal, "could not lock room") + ErrRoomUnlockFailed = psrpc.NewErrorf(psrpc.Internal, "could not unlock room, lock token does not match") + ErrTrackNotFound = psrpc.NewErrorf(psrpc.NotFound, "track is not found") + ErrWebHookMissingAPIKey = psrpc.NewErrorf(psrpc.InvalidArgument, "api_key is required to use webhooks") ) diff --git a/pkg/service/server.go b/pkg/service/server.go index acc6ffa7..575794b2 100644 --- a/pkg/service/server.go +++ b/pkg/service/server.go @@ -83,8 +83,9 @@ func NewLivekitServer(conf *config.Config, } twirpLoggingHook := TwirpLogger(logger.GetLogger()) + twirpRequestStatusHook := TwirpRequestStatusReporter() roomServer := livekit.NewRoomServiceServer(roomService, twirpLoggingHook) - egressServer := livekit.NewEgressServer(egressService, twirpLoggingHook) + egressServer := livekit.NewEgressServer(egressService, twirpLoggingHook, twirpRequestStatusHook) ingressServer := livekit.NewIngressServer(ingressService, twirpLoggingHook) mux := http.NewServeMux() diff --git a/pkg/service/twirp.go b/pkg/service/twirp.go index 4c36c271..f5761625 100644 --- a/pkg/service/twirp.go +++ b/pkg/service/twirp.go @@ -18,18 +18,27 @@ package service import ( "context" + "strconv" "sync" "time" "github.com/twitchtv/twirp" + "github.com/livekit/livekit-server/pkg/telemetry/prometheus" "github.com/livekit/protocol/logger" ) var ( - loggerKey = struct{}{} + loggerKey = struct{}{} + statusReporterKey = struct{ a int }{42} ) +type twirpRequestFields struct { + service string + method string + error twirp.Error +} + // logging handling inspired by https://github.com/bakins/twirpzap // License: Apache-2.0 func TwirpLogger(logger logger.Logger) *twirp.ServerHooks { @@ -54,10 +63,9 @@ func TwirpLogger(logger logger.Logger) *twirp.ServerHooks { } type requestLogger struct { + twirpRequestFields + logger logger.Logger - service string - method string - error twirp.Error fieldsOrig []interface{} fields []interface{} startedAt time.Time @@ -135,3 +143,74 @@ func errorReceived(ctx context.Context, e twirp.Error) context.Context { return ctx } + +func TwirpRequestStatusReporter() *twirp.ServerHooks { + return &twirp.ServerHooks{ + RequestReceived: statusReporterRequestReceived, + RequestRouted: statusReporterResponseRouted, + Error: statusReporterErrorReceived, + ResponseSent: statusReporterResponseSent, + } +} + +func statusReporterRequestReceived(ctx context.Context) (context.Context, error) { + r := &twirpRequestFields{} + + if svc, ok := twirp.ServiceName(ctx); ok { + r.service = svc + } + + ctx = context.WithValue(ctx, statusReporterKey, r) + return ctx, nil +} + +func statusReporterResponseRouted(ctx context.Context) (context.Context, error) { + if meth, ok := twirp.MethodName(ctx); ok { + l, ok := ctx.Value(statusReporterKey).(*twirpRequestFields) + if !ok || l == nil { + return ctx, nil + } + l.method = meth + } + + return ctx, nil +} + +func statusReporterResponseSent(ctx context.Context) { + r, ok := ctx.Value(statusReporterKey).(*twirpRequestFields) + if !ok || r == nil { + return + } + + var statusFamily string + if statusCode, ok := twirp.StatusCode(ctx); ok { + if status, err := strconv.Atoi(statusCode); err != nil { + switch { + case status >= 400 && status <= 499: + statusFamily = "4xx" + case status >= 500 && status <= 599: + statusFamily = "5xx" + default: + statusFamily = strconv.Itoa(status) + } + } + } + + var code twirp.ErrorCode + if r.error != nil { + code = r.error.Code() + } + + prometheus.TwirpRequestStatusCounter.WithLabelValues(r.service, r.method, statusFamily, string(code)).Add(1) +} + +func statusReporterErrorReceived(ctx context.Context, e twirp.Error) context.Context { + r, ok := ctx.Value(statusReporterKey).(*twirpRequestFields) + if !ok || r == nil { + return ctx + } + + r.error = e + + return ctx +} diff --git a/pkg/telemetry/prometheus/node.go b/pkg/telemetry/prometheus/node.go index f9ad5e16..baedd2ed 100644 --- a/pkg/telemetry/prometheus/node.go +++ b/pkg/telemetry/prometheus/node.go @@ -19,8 +19,9 @@ const ( var ( initialized atomic.Bool - MessageCounter *prometheus.CounterVec - ServiceOperationCounter *prometheus.CounterVec + MessageCounter *prometheus.CounterVec + ServiceOperationCounter *prometheus.CounterVec + TwirpRequestStatusCounter *prometheus.CounterVec sysPacketsStart uint32 sysDroppedPacketsStart uint32 @@ -53,6 +54,16 @@ func Init(nodeID string, nodeType livekit.NodeType) { []string{"type", "status", "error_type"}, ) + TwirpRequestStatusCounter = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: livekitNamespace, + Subsystem: "node", + Name: "twirp_request_status", + ConstLabels: prometheus.Labels{"node_id": nodeID, "node_type": nodeType.String()}, + }, + []string{"service", "method", "status", "code"}, + ) + promSysPacketGauge = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: livekitNamespace, @@ -76,6 +87,7 @@ func Init(nodeID string, nodeType livekit.NodeType) { prometheus.MustRegister(MessageCounter) prometheus.MustRegister(ServiceOperationCounter) + prometheus.MustRegister(TwirpRequestStatusCounter) prometheus.MustRegister(promSysPacketGauge) prometheus.MustRegister(promSysDroppedPacketPctGauge)