forked from linkerd/linkerd2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtop_routes.go
370 lines (320 loc) · 10.6 KB
/
top_routes.go
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package api
import (
"context"
"errors"
"fmt"
"sort"
"strings"
sp "github.com/linkerd/linkerd2/controller/gen/apis/serviceprofile/v1alpha2"
api "github.com/linkerd/linkerd2/controller/k8s"
"github.com/linkerd/linkerd2/pkg/k8s"
pb "github.com/linkerd/linkerd2/viz/metrics-api/gen/viz"
"github.com/prometheus/common/model"
log "github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
)
const (
routeReqQuery = "sum(increase(route_response_total%s[%s])) by (%s, dst, classification)"
actualRouteReqQuery = "sum(increase(route_actual_response_total%s[%s])) by (%s, dst, classification)"
routeLatencyQuantileQuery = "histogram_quantile(%s, sum(irate(route_response_latency_ms_bucket%s[%s])) by (le, dst, %s))"
dstLabel = `dst=~"(%s)(:\\d+)?"`
// DefaultRouteName is the name to display for requests that don't match any routes.
DefaultRouteName = "[DEFAULT]"
)
type dstAndRoute struct {
dst string
route string
}
type indexedTable = map[dstAndRoute]*pb.RouteTable_Row
type resourceTable struct {
resource string
table indexedTable
}
func (s *grpcServer) TopRoutes(ctx context.Context, req *pb.TopRoutesRequest) (*pb.TopRoutesResponse, error) {
log.Debugf("TopRoutes request: %+v", req)
if !s.k8sAPI.SPAvailable() {
return topRoutesError(req, "Routes are not available"), nil
}
errRsp := validateRequest(req)
if errRsp != nil {
return errRsp, nil
}
// TopRoutes will return one table for each resource object requested.
tables := make([]resourceTable, 0)
targetResource := req.GetSelector().GetResource()
labelSelector, err := getTopLabelSelector(req)
if err != nil {
return nil, err
}
if targetResource.GetType() == k8s.Authority {
// Authority cannot be the target because authorities don't have namespaces,
// therefore there is no namespace in which to look for a service profile.
return topRoutesError(req, "Authority cannot be the target of a routes query; try using an authority in the --to flag instead"), nil
}
// Non-authority resource
objects, err := s.k8sAPI.GetObjects(targetResource.Namespace, targetResource.Type, targetResource.Name, labelSelector)
if err != nil {
return nil, err
}
// Create a table for each object in the resource.
for _, obj := range objects {
table, err := s.topRoutesFor(ctx, req, obj)
if err != nil {
// No samples for this object, skip it.
continue
}
tables = append(tables, *table)
}
if len(tables) == 0 {
return topRoutesError(req, "No Service Profiles found for selected resources"), nil
}
// Construct response.
routeTables := make([]*pb.RouteTable, 0)
for _, t := range tables {
rows := make([]*pb.RouteTable_Row, 0)
for _, row := range t.table {
rows = append(rows, row)
}
routeTables = append(routeTables, &pb.RouteTable{
Resource: t.resource,
Rows: rows,
})
}
return &pb.TopRoutesResponse{
Response: &pb.TopRoutesResponse_Ok_{
Ok: &pb.TopRoutesResponse_Ok{
Routes: routeTables,
},
},
}, nil
}
// topRoutesFor constructs a resource table for the given resource object.
func (s *grpcServer) topRoutesFor(ctx context.Context, req *pb.TopRoutesRequest, object runtime.Object) (*resourceTable, error) {
// requestedResource is the destination resource. For inbound queries, it is the target resource.
// For outbound (i.e. --to) queries, it is the ToResource. We will look at the service profiles
// of this destination resource.
name, err := api.GetNameOf(object)
if err != nil {
return nil, err
}
clientNs := req.GetSelector().GetResource().GetNamespace()
typ := req.GetSelector().GetResource().GetType()
labelSelector, err := getTopLabelSelector(req)
if err != nil {
return nil, err
}
targetResource := &pb.Resource{
Name: name,
Namespace: req.GetSelector().GetResource().GetNamespace(),
Type: typ,
}
requestedResource := targetResource
if req.GetToResource() != nil {
requestedResource = req.GetToResource()
}
profiles := make(map[string]*sp.ServiceProfile)
if requestedResource.GetType() == k8s.Authority {
// Authorities may not be a source, so we know this is a ToResource.
profiles, err = s.getProfilesForAuthority(requestedResource.GetName(), clientNs, labelSelector)
if err != nil {
return nil, err
}
} else {
// Non-authority resource.
// Lookup individual resource objects.
objects, err := s.k8sAPI.GetObjects(requestedResource.Namespace, requestedResource.Type, requestedResource.Name, labelSelector)
if err != nil {
return nil, err
}
// Find service profiles for all services in all objects in the resource.
for _, obj := range objects {
// Lookup services for each object.
services, err := s.k8sAPI.GetServicesFor(obj, false)
if err != nil {
return nil, err
}
for _, svc := range services {
p := s.k8sAPI.GetServiceProfileFor(svc, clientNs, s.clusterDomain)
profiles[svc.GetName()] = p
}
}
}
metrics, err := s.getRouteMetrics(ctx, req, profiles, targetResource)
if err != nil {
return nil, err
}
return &resourceTable{
resource: fmt.Sprintf("%s/%s", typ, name),
table: metrics,
}, nil
}
func topRoutesError(req *pb.TopRoutesRequest, message string) *pb.TopRoutesResponse {
return &pb.TopRoutesResponse{
Response: &pb.TopRoutesResponse_Error{
Error: &pb.ResourceError{
Resource: req.GetSelector().GetResource(),
Error: message,
},
},
}
}
func validateRequest(req *pb.TopRoutesRequest) *pb.TopRoutesResponse {
if req.GetSelector().GetResource() == nil {
return topRoutesError(req, "TopRoutes request missing Selector Resource")
}
if req.GetNone() == nil {
// This is an outbound (--to) request.
targetType := req.GetSelector().GetResource().GetType()
if targetType == k8s.Service || targetType == k8s.Authority {
return topRoutesError(req, fmt.Sprintf("The %s resource type is not supported with 'to' queries", targetType))
}
}
return nil
}
func (s *grpcServer) getProfilesForAuthority(authority string, clientNs string, labelSelector labels.Selector) (map[string]*sp.ServiceProfile, error) {
if authority == "" {
// All authorities
ps, err := s.k8sAPI.SP().Lister().ServiceProfiles(clientNs).List(labelSelector)
if err != nil {
return nil, err
}
if len(ps) == 0 {
return nil, errors.New("No ServiceProfiles found")
}
profiles := make(map[string]*sp.ServiceProfile)
for _, p := range ps {
profiles[p.Name] = p
}
return profiles, nil
}
// Specific authority
p, err := s.k8sAPI.SP().Lister().ServiceProfiles(clientNs).Get(authority)
if err != nil {
return nil, err
}
return map[string]*sp.ServiceProfile{
p.Name: p,
}, nil
}
func (s *grpcServer) getRouteMetrics(ctx context.Context, req *pb.TopRoutesRequest, profiles map[string]*sp.ServiceProfile, resource *pb.Resource) (indexedTable, error) {
timeWindow := req.TimeWindow
dsts := make([]string, 0)
for _, p := range profiles {
dsts = append(dsts, p.GetName())
}
reqLabels := s.buildRouteLabels(req, dsts, resource)
groupBy := "rt_route"
queries := map[promType]string{
promRequests: fmt.Sprintf(routeReqQuery, reqLabels, timeWindow, groupBy),
}
if req.GetOutbound() != nil && req.GetNone() == nil {
// If this req has an Outbound, then query the actual request counts as well.
queries[promActualRequests] = fmt.Sprintf(actualRouteReqQuery, reqLabels, timeWindow, groupBy)
}
quantileQueries := generateQuantileQueries(routeLatencyQuantileQuery, reqLabels, timeWindow, groupBy)
results, err := s.getPrometheusMetrics(ctx, queries, quantileQueries)
if err != nil {
return nil, err
}
table := make(indexedTable)
for service, profile := range profiles {
for _, route := range profile.Spec.Routes {
key := dstAndRoute{
dst: profile.GetName(),
route: route.Name,
}
table[key] = &pb.RouteTable_Row{
Authority: service,
Route: route.Name,
Stats: &pb.BasicStats{},
}
}
defaultKey := dstAndRoute{
dst: profile.GetName(),
route: "",
}
table[defaultKey] = &pb.RouteTable_Row{
Authority: service,
Route: DefaultRouteName,
Stats: &pb.BasicStats{},
}
}
processRouteMetrics(results, timeWindow, table)
return table, nil
}
func (s *grpcServer) buildRouteLabels(req *pb.TopRoutesRequest, dsts []string, resource *pb.Resource) string {
// labels: the labels for the resource we want to query for
var labels model.LabelSet
switch req.Outbound.(type) {
case *pb.TopRoutesRequest_ToResource:
labels = labels.Merge(promQueryLabels(resource))
labels = labels.Merge(promDirectionLabels("outbound"))
return renderLabels(labels, dsts)
default:
labels = labels.Merge(promDirectionLabels("inbound"))
labels = labels.Merge(promQueryLabels(resource))
return renderLabels(labels, dsts)
}
}
func renderLabels(labels model.LabelSet, services []string) string {
pairs := make([]string, 0)
for k, v := range labels {
pairs = append(pairs, fmt.Sprintf("%s=%q", k, v))
}
if len(services) > 0 {
pairs = append(pairs, fmt.Sprintf(dstLabel, strings.Join(services, "|")))
}
sort.Strings(pairs)
return fmt.Sprintf("{%s}", strings.Join(pairs, ", "))
}
func processRouteMetrics(results []promResult, timeWindow string, table indexedTable) {
for _, result := range results {
for _, sample := range result.vec {
route := string(sample.Metric[model.LabelName("rt_route")])
dst := string(sample.Metric[model.LabelName("dst")])
dst = strings.Split(dst, ":")[0] // Truncate port, if there is one.
key := dstAndRoute{dst, route}
if table[key] == nil {
log.Warnf("Found stats for unknown route: %s:%s", dst, route)
continue
}
table[key].TimeWindow = timeWindow
value := extractSampleValue(sample)
switch result.prom {
case promRequests:
switch string(sample.Metric[model.LabelName("classification")]) {
case success:
table[key].Stats.SuccessCount += value
case failure:
table[key].Stats.FailureCount += value
}
case promActualRequests:
switch string(sample.Metric[model.LabelName("classification")]) {
case success:
table[key].Stats.ActualSuccessCount += value
case failure:
table[key].Stats.ActualFailureCount += value
}
case promLatencyP50:
table[key].Stats.LatencyMsP50 = value
case promLatencyP95:
table[key].Stats.LatencyMsP95 = value
case promLatencyP99:
table[key].Stats.LatencyMsP99 = value
}
}
}
}
// generate correct label.Selector object according to the request
func getTopLabelSelector(req *pb.TopRoutesRequest) (labels.Selector, error) {
labelSelector := labels.Everything()
if s := req.GetSelector().GetLabelSelector(); s != "" {
var err error
labelSelector, err = labels.Parse(s)
if err != nil {
return nil, fmt.Errorf("invalid label selector %q: %w", s, err)
}
}
return labelSelector, nil
}