Welcome to mirror list, hosted at ThFree Co, Russian Federation.

sentryhandler.go « sentryhandler « middleware « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 2466f494402deb610f4e1295760ed258ae10e8a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package sentryhandler

import (
	"context"
	"fmt"
	"reflect"
	"regexp"
	"strings"
	"time"

	sentry "github.com/getsentry/sentry-go"
	grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
	"gitlab.com/gitlab-org/gitaly/internal/helper"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
)

const (
	skipSubmission = "sentry.skip"
)

var ignoredCodes = []codes.Code{
	// OK means there was no error
	codes.OK,
	// Canceled and DeadlineExceeded indicate clients that disappeared or lost interest
	codes.Canceled,
	codes.DeadlineExceeded,
	// We use FailedPrecondition to signal error conditions that are 'normal'
	codes.FailedPrecondition,
}

// UnaryLogHandler handles access times and errors for unary RPC's
func UnaryLogHandler(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
	start := time.Now()
	resp, err := handler(ctx, req)

	if err != nil {
		logGrpcErrorToSentry(ctx, info.FullMethod, start, err)
	}

	return resp, err
}

// StreamLogHandler handles access times and errors for stream RPC's
func StreamLogHandler(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
	start := time.Now()
	err := handler(srv, stream)

	if err != nil {
		logGrpcErrorToSentry(stream.Context(), info.FullMethod, start, err)
	}

	return err
}

func stringMap(incoming map[string]interface{}) map[string]string {
	result := make(map[string]string)
	for i, v := range incoming {
		result[i] = fmt.Sprintf("%v", v)
	}
	return result
}

func methodToCulprit(methodName string) string {
	methodName = strings.TrimPrefix(methodName, "/gitaly.")
	methodName = strings.Replace(methodName, "/", "::", 1)
	return methodName
}

func logErrorToSentry(ctx context.Context, err error) (code codes.Code, bypass bool) {
	code = helper.GrpcCode(err)

	for _, ignoredCode := range ignoredCodes {
		if code == ignoredCode {
			return code, true
		}
	}

	tags := grpc_ctxtags.Extract(ctx)
	if tags.Has(skipSubmission) {
		return code, true
	}

	return code, false
}

func generateSentryEvent(ctx context.Context, method string, start time.Time, err error) *sentry.Event {
	grpcErrorCode, bypass := logErrorToSentry(ctx, err)
	if bypass {
		return nil
	}

	tags := grpc_ctxtags.Extract(ctx)
	event := sentry.NewEvent()

	for k, v := range stringMap(tags.Values()) {
		event.Tags[k] = v
	}

	for k, v := range map[string]string{
		"grpc.code":    grpcErrorCode.String(),
		"grpc.method":  method,
		"grpc.time_ms": fmt.Sprintf("%d", time.Since(start).Milliseconds()),
		"system":       "grpc",
	} {
		event.Tags[k] = v
	}

	event.Message = err.Error()

	// Skip the stacktrace as it's not helpful in this context
	event.Exception = append(event.Exception, newException(err, nil))

	grpcMethod := methodToCulprit(method)

	// Details on fingerprinting
	// https://docs.sentry.io/learn/rollups/#customize-grouping-with-fingerprints
	event.Fingerprint = []string{"grpc", grpcMethod, grpcErrorCode.String()}
	event.Transaction = grpcMethod

	return event
}

func logGrpcErrorToSentry(ctx context.Context, method string, start time.Time, err error) {
	event := generateSentryEvent(ctx, method, start, err)
	if event == nil {
		return
	}

	sentry.CaptureEvent(event)
}

var errorMsgPattern = regexp.MustCompile(`\A(\w+): (.+)\z`)

// newException constructs an Exception using provided Error and Stacktrace
func newException(err error, stacktrace *sentry.Stacktrace) sentry.Exception {
	msg := err.Error()
	ex := sentry.Exception{
		Stacktrace: stacktrace,
		Value:      msg,
		Type:       reflect.TypeOf(err).String(),
	}
	if m := errorMsgPattern.FindStringSubmatch(msg); m != nil {
		ex.Module, ex.Value = m[1], m[2]
	}
	return ex
}

// MarkToSkip propagate context with a special tag that signals to sentry handler that the error must not be reported.
func MarkToSkip(ctx context.Context) {
	tags := grpc_ctxtags.Extract(ctx)
	tags.Set(skipSubmission, struct{}{})
}