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

metadatahandler.go « metadatahandler « middleware « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bae12151e9d16ebd6e4fd01d8cc949fec1163857 (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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package metadatahandler

import (
	"context"
	"strings"

	grpcmwtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
	grpcprometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	gitalyauth "gitlab.com/gitlab-org/gitaly/v16/auth"
	"gitlab.com/gitlab-org/gitaly/v16/internal/structerr"
	"gitlab.com/gitlab-org/labkit/correlation"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

var requests = promauto.NewCounterVec(
	prometheus.CounterOpts{
		Name: "gitaly_service_client_requests_total",
		Help: "Counter of client requests received by client, call_site, auth version, response code and deadline_type",
	},
	[]string{
		"client_name",
		"grpc_service",
		"grpc_method",
		"call_site",
		"auth_version",
		"grpc_code",
		"deadline_type",
	},
)

type metadataTags struct {
	clientName   string
	callSite     string
	authVersion  string
	deadlineType string
}

// CallSiteKey is the key used in ctx_tags to store the client feature
const CallSiteKey = "grpc.meta.call_site"

// ClientNameKey is the key used in ctx_tags to store the client name
const ClientNameKey = "grpc.meta.client_name"

// AuthVersionKey is the key used in ctx_tags to store the auth version
const AuthVersionKey = "grpc.meta.auth_version"

// DeadlineTypeKey is the key used in ctx_tags to store the deadline type
const DeadlineTypeKey = "grpc.meta.deadline_type"

// MethodTypeKey is one of "unary", "client_stream", "server_stream", "bidi_stream"
const MethodTypeKey = "grpc.meta.method_type"

// RemoteIPKey is the key used in ctx_tags to store the remote_ip
const RemoteIPKey = "remote_ip"

// UserIDKey is the key used in ctx_tags to store the user_id
const UserIDKey = "user_id"

// UsernameKey is the key used in ctx_tags to store the username
const UsernameKey = "username"

// CorrelationIDKey is the key used in ctx_tags to store the correlation ID
const CorrelationIDKey = "correlation_id"

// Unknown client and feature. Matches the prometheus grpc unknown value
const unknownValue = "unknown"

func getFromMD(md metadata.MD, header string) string {
	values := md[header]
	if len(values) != 1 {
		return ""
	}

	return values[0]
}

// addMetadataTags extracts metadata from the connection headers and add it to the
// ctx_tags, if it is set. Returns values appropriate for use with prometheus labels,
// using `unknown` if a value is not set
func addMetadataTags(ctx context.Context, grpcMethodType string) metadataTags {
	metaTags := metadataTags{
		clientName:   unknownValue,
		callSite:     unknownValue,
		authVersion:  unknownValue,
		deadlineType: unknownValue,
	}

	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return metaTags
	}

	tags := grpcmwtags.Extract(ctx)

	metadata := getFromMD(md, "call_site")
	if metadata != "" {
		metaTags.callSite = metadata
		tags.Set(CallSiteKey, metadata)
	}

	metadata = getFromMD(md, "deadline_type")
	_, deadlineSet := ctx.Deadline()
	if !deadlineSet {
		metaTags.deadlineType = "none"
	} else if metadata != "" {
		metaTags.deadlineType = metadata
	}

	clientName := correlation.ExtractClientNameFromContext(ctx)
	if clientName != "" {
		metaTags.clientName = clientName
		tags.Set(ClientNameKey, clientName)
	} else {
		metadata = getFromMD(md, "client_name")
		if metadata != "" {
			metaTags.clientName = metadata
			tags.Set(ClientNameKey, metadata)
		}
	}

	// Set the deadline and method types in the logs
	tags.Set(DeadlineTypeKey, metaTags.deadlineType)
	tags.Set(MethodTypeKey, grpcMethodType)

	authInfo, _ := gitalyauth.ExtractAuthInfo(ctx)
	if authInfo != nil {
		metaTags.authVersion = authInfo.Version
		tags.Set(AuthVersionKey, authInfo.Version)
	}

	metadata = getFromMD(md, "remote_ip")
	if metadata != "" {
		tags.Set(RemoteIPKey, metadata)
	}

	metadata = getFromMD(md, "user_id")
	if metadata != "" {
		tags.Set(UserIDKey, metadata)
	}

	metadata = getFromMD(md, "username")
	if metadata != "" {
		tags.Set(UsernameKey, metadata)
	}

	// This is a stop-gap approach to logging correlation_ids
	correlationID := correlation.ExtractFromContext(ctx)
	if correlationID != "" {
		tags.Set(CorrelationIDKey, correlationID)
	}

	return metaTags
}

func extractServiceAndMethodName(fullMethodName string) (string, string) {
	fullMethodName = strings.TrimPrefix(fullMethodName, "/") // remove leading slash
	service, method, ok := strings.Cut(fullMethodName, "/")
	if !ok {
		return unknownValue, unknownValue
	}
	return service, method
}

func streamRPCType(info *grpc.StreamServerInfo) string {
	if info.IsClientStream && !info.IsServerStream {
		return "client_stream"
	} else if !info.IsClientStream && info.IsServerStream {
		return "server_stream"
	}
	return "bidi_stream"
}

func reportWithPrometheusLabels(metaTags metadataTags, fullMethod string, err error) {
	grpcCode := structerr.GRPCCode(err)
	serviceName, methodName := extractServiceAndMethodName(fullMethod)

	requests.WithLabelValues(
		metaTags.clientName,   // client_name
		serviceName,           // grpc_service
		methodName,            // grpc_method
		metaTags.callSite,     // call_site
		metaTags.authVersion,  // auth_version
		grpcCode.String(),     // grpc_code
		metaTags.deadlineType, // deadline_type
	).Inc()
	grpcprometheus.WithConstLabels(prometheus.Labels{"deadline_type": metaTags.deadlineType})
}

// UnaryInterceptor returns a Unary Interceptor
func UnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
	metaTags := addMetadataTags(ctx, "unary")

	res, err := handler(ctx, req)

	reportWithPrometheusLabels(metaTags, info.FullMethod, err)

	return res, err
}

// StreamInterceptor returns a Stream Interceptor
func StreamInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
	ctx := stream.Context()
	metaTags := addMetadataTags(ctx, streamRPCType(info))

	err := handler(srv, stream)

	reportWithPrometheusLabels(metaTags, info.FullMethod, err)

	return err
}