-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
api_utils.go
498 lines (446 loc) · 12.7 KB
/
api_utils.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package util
import (
"errors"
"fmt"
"strings"
"time"
pb "github.com/linkerd/linkerd2/controller/gen/public"
"github.com/linkerd/linkerd2/pkg/addr"
"github.com/linkerd/linkerd2/pkg/k8s"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/api/core/v1"
k8sErrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
/*
Shared utilities for interacting with the controller public api
*/
var (
defaultMetricTimeWindow = "1m"
// ValidTargets specifies resource types allowed as a target:
// target resource on an inbound query
// target resource on an outbound 'to' query
// destination resource on an outbound 'from' query
ValidTargets = []string{
k8s.Deployment,
k8s.Namespace,
k8s.Pod,
k8s.ReplicationController,
k8s.Authority,
}
// ValidDestinations specifies resource types allowed as a destination:
// destination resource on an outbound 'to' query
// target resource on an outbound 'from' query
ValidDestinations = []string{
k8s.Deployment,
k8s.Namespace,
k8s.Pod,
k8s.ReplicationController,
k8s.Service,
}
)
type StatSummaryRequestParams struct {
TimeWindow string
Namespace string
ResourceType string
ResourceName string
ToNamespace string
ToType string
ToName string
FromNamespace string
FromType string
FromName string
AllNamespaces bool
}
type TapRequestParams struct {
Resource string
Namespace string
ToResource string
ToNamespace string
MaxRps float32
Scheme string
Method string
Authority string
Path string
}
// GRPCError generates a gRPC error code, as defined in
// google.golang.org/grpc/status.
// If the error is nil or already a gRPC error, return the error.
// If the error is of type k8s.io/apimachinery/pkg/apis/meta/v1#StatusReason,
// attempt to map the reason to a gRPC error.
func GRPCError(err error) error {
if err != nil && status.Code(err) == codes.Unknown {
code := codes.Internal
switch k8sErrors.ReasonForError(err) {
case metav1.StatusReasonUnknown:
code = codes.Unknown
case metav1.StatusReasonUnauthorized, metav1.StatusReasonForbidden:
code = codes.PermissionDenied
case metav1.StatusReasonNotFound:
code = codes.NotFound
case metav1.StatusReasonAlreadyExists:
code = codes.AlreadyExists
case metav1.StatusReasonInvalid:
code = codes.InvalidArgument
case metav1.StatusReasonExpired:
code = codes.DeadlineExceeded
case metav1.StatusReasonServiceUnavailable:
code = codes.Unavailable
}
err = status.Error(code, err.Error())
}
return err
}
func BuildStatSummaryRequest(p StatSummaryRequestParams) (*pb.StatSummaryRequest, error) {
window := defaultMetricTimeWindow
if p.TimeWindow != "" {
_, err := time.ParseDuration(p.TimeWindow)
if err != nil {
return nil, err
}
window = p.TimeWindow
}
if p.AllNamespaces && p.ResourceName != "" {
return nil, errors.New("stats for a resource cannot be retrieved by name across all namespaces")
}
targetNamespace := p.Namespace
if p.AllNamespaces {
targetNamespace = ""
} else if p.Namespace == "" {
targetNamespace = v1.NamespaceDefault
}
resourceType, err := k8s.CanonicalResourceNameFromFriendlyName(p.ResourceType)
if err != nil {
return nil, err
}
statRequest := &pb.StatSummaryRequest{
Selector: &pb.ResourceSelection{
Resource: &pb.Resource{
Namespace: targetNamespace,
Name: p.ResourceName,
Type: resourceType,
},
},
TimeWindow: window,
}
if p.ToName != "" || p.ToType != "" || p.ToNamespace != "" {
if p.ToNamespace == "" {
p.ToNamespace = targetNamespace
}
if p.ToType == "" {
p.ToType = resourceType
}
toType, err := k8s.CanonicalResourceNameFromFriendlyName(p.ToType)
if err != nil {
return nil, err
}
toResource := pb.StatSummaryRequest_ToResource{
ToResource: &pb.Resource{
Namespace: p.ToNamespace,
Type: toType,
Name: p.ToName,
},
}
statRequest.Outbound = &toResource
}
if p.FromName != "" || p.FromType != "" || p.FromNamespace != "" {
if p.FromNamespace == "" {
p.FromNamespace = targetNamespace
}
if p.FromType == "" {
p.FromType = resourceType
}
fromType, err := validateFromResourceType(p.FromType)
if err != nil {
return nil, err
}
fromResource := pb.StatSummaryRequest_FromResource{
FromResource: &pb.Resource{
Namespace: p.FromNamespace,
Type: fromType,
Name: p.FromName,
},
}
statRequest.Outbound = &fromResource
}
return statRequest, nil
}
// An authority can only receive traffic, not send it, so it can't be a --from
func validateFromResourceType(resourceType string) (string, error) {
name, err := k8s.CanonicalResourceNameFromFriendlyName(resourceType)
if err != nil {
return "", err
}
if name == k8s.Authority {
return "", errors.New("cannot query traffic --from an authority")
}
return name, nil
}
// BuildResource parses input strings, typically from CLI flags, to build a
// Resource object for use in the protobuf API.
func BuildResource(namespace string, args ...string) (pb.Resource, error) {
switch len(args) {
case 0:
return pb.Resource{}, errors.New("No resource arguments provided")
case 1:
elems := strings.Split(args[0], "/")
switch len(elems) {
case 1:
// --namespace my-ns deploy
return buildResource(namespace, elems[0], "")
case 2:
// --namespace my-ns deploy/foo
return buildResource(namespace, elems[0], elems[1])
default:
return pb.Resource{}, errors.New("Invalid resource string: " + args[0])
}
case 2:
// --namespace my-ns deploy foo
return buildResource(namespace, args[0], args[1])
default:
return pb.Resource{}, errors.New("Too many arguments provided for resource: " + strings.Join(args, "/"))
}
}
func buildResource(namespace string, resType string, name string) (pb.Resource, error) {
canonicalType, err := k8s.CanonicalResourceNameFromFriendlyName(resType)
if err != nil {
return pb.Resource{}, err
}
if canonicalType == k8s.Namespace {
// ignore --namespace flags if type is namespace
namespace = ""
}
return pb.Resource{
Namespace: namespace,
Type: canonicalType,
Name: name,
}, nil
}
func BuildTapByResourceRequest(params TapRequestParams) (*pb.TapByResourceRequest, error) {
target, err := BuildResource(params.Namespace, params.Resource)
if err != nil {
return nil, fmt.Errorf("target resource invalid: %s", err)
}
if !contains(ValidTargets, target.Type) {
return nil, fmt.Errorf("unsupported resource type [%s]", target.Type)
}
matches := []*pb.TapByResourceRequest_Match{}
if params.ToResource != "" {
destination, err := BuildResource(params.ToNamespace, params.ToResource)
if err != nil {
return nil, fmt.Errorf("destination resource invalid: %s", err)
}
if !contains(ValidDestinations, destination.Type) {
return nil, fmt.Errorf("unsupported resource type [%s]", target.Type)
}
match := pb.TapByResourceRequest_Match{
Match: &pb.TapByResourceRequest_Match_Destinations{
Destinations: &pb.ResourceSelection{
Resource: &destination,
},
},
}
matches = append(matches, &match)
}
if params.Scheme != "" {
match := buildMatchHTTP(&pb.TapByResourceRequest_Match_Http{
Match: &pb.TapByResourceRequest_Match_Http_Scheme{Scheme: params.Scheme},
})
matches = append(matches, &match)
}
if params.Method != "" {
match := buildMatchHTTP(&pb.TapByResourceRequest_Match_Http{
Match: &pb.TapByResourceRequest_Match_Http_Method{Method: params.Method},
})
matches = append(matches, &match)
}
if params.Authority != "" {
match := buildMatchHTTP(&pb.TapByResourceRequest_Match_Http{
Match: &pb.TapByResourceRequest_Match_Http_Authority{Authority: params.Authority},
})
matches = append(matches, &match)
}
if params.Path != "" {
match := buildMatchHTTP(&pb.TapByResourceRequest_Match_Http{
Match: &pb.TapByResourceRequest_Match_Http_Path{Path: params.Path},
})
matches = append(matches, &match)
}
return &pb.TapByResourceRequest{
Target: &pb.ResourceSelection{
Resource: &target,
},
MaxRps: params.MaxRps,
Match: &pb.TapByResourceRequest_Match{
Match: &pb.TapByResourceRequest_Match_All{
All: &pb.TapByResourceRequest_Match_Seq{
Matches: matches,
},
},
},
}, nil
}
func buildMatchHTTP(match *pb.TapByResourceRequest_Match_Http) pb.TapByResourceRequest_Match {
return pb.TapByResourceRequest_Match{
Match: &pb.TapByResourceRequest_Match_Http_{
Http: match,
},
}
}
func contains(list []string, s string) bool {
for _, elem := range list {
if s == elem {
return true
}
}
return false
}
type peer struct {
address *pb.TcpAddress
labels map[string]string
direction string
}
// src returns the source peer of a `TapEvent`.
func src(event *pb.TapEvent) peer {
return peer{
address: event.GetSource(),
labels: event.GetSourceMeta().GetLabels(),
direction: "src",
}
}
// dst returns the destination peer of a `TapEvent`.
func dst(event *pb.TapEvent) peer {
return peer{
address: event.GetDestination(),
labels: event.GetDestinationMeta().GetLabels(),
direction: "dst",
}
}
// formatAddr formats the peer's TCP address for the `src` or `dst` element in
// the tap output corresponding to this peer.
func (p *peer) formatAddr() string {
return fmt.Sprintf(
"%s=%s",
p.direction,
addr.PublicAddressToString(p.address),
)
}
// formatResource returns a label describing what Kubernetes resources the peer
// belongs to. If the peer belongs to a resource of kind `resourceKind`, it will
// return a label for that resource; otherwise, it will fall back to the peer's
// pod name. Additionally, if the resource is not of type `namespace`, it will
// also add a label describing the peer's resource.
func (p *peer) formatResource(resourceKind string) string {
var s string
if resourceName, exists := p.labels[resourceKind]; exists {
kind := resourceKind
if short := k8s.ShortNameFromCanonicalResourceName(resourceKind); short != "" {
kind = short
}
s = fmt.Sprintf(
" %s_res=%s/%s",
p.direction,
kind,
resourceName,
)
} else if pod, hasPod := p.labels[k8s.Pod]; hasPod {
s = fmt.Sprintf(" %s_pod=%s", p.direction, pod)
}
if resourceKind != k8s.Namespace {
if ns, hasNs := p.labels[k8s.Namespace]; hasNs {
s += fmt.Sprintf(" %s_ns=%s", p.direction, ns)
}
}
return s
}
func (p *peer) tlsStatus() string {
return p.labels["tls"]
}
func RenderTapEvent(event *pb.TapEvent, resource string) string {
dst := dst(event)
src := src(event)
proxy := "???"
tls := ""
switch event.GetProxyDirection() {
case pb.TapEvent_INBOUND:
proxy = "in " // A space is added so it aligns with `out`.
tls = src.tlsStatus()
case pb.TapEvent_OUTBOUND:
proxy = "out"
tls = dst.tlsStatus()
default:
// Too old for TLS.
}
flow := fmt.Sprintf("proxy=%s %s %s tls=%s",
proxy,
src.formatAddr(),
dst.formatAddr(),
tls,
)
resources := ""
if resource != "" {
resources = fmt.Sprintf(
"%s%s",
src.formatResource(resource),
dst.formatResource(resource),
)
}
switch ev := event.GetHttp().GetEvent().(type) {
case *pb.TapEvent_Http_RequestInit_:
return fmt.Sprintf("req id=%d:%d %s :method=%s :authority=%s :path=%s%s",
ev.RequestInit.GetId().GetBase(),
ev.RequestInit.GetId().GetStream(),
flow,
ev.RequestInit.GetMethod().GetRegistered().String(),
ev.RequestInit.GetAuthority(),
ev.RequestInit.GetPath(),
resources,
)
case *pb.TapEvent_Http_ResponseInit_:
return fmt.Sprintf("rsp id=%d:%d %s :status=%d latency=%dµs%s",
ev.ResponseInit.GetId().GetBase(),
ev.ResponseInit.GetId().GetStream(),
flow,
ev.ResponseInit.GetHttpStatus(),
ev.ResponseInit.GetSinceRequestInit().GetNanos()/1000,
resources,
)
case *pb.TapEvent_Http_ResponseEnd_:
switch eos := ev.ResponseEnd.GetEos().GetEnd().(type) {
case *pb.Eos_GrpcStatusCode:
return fmt.Sprintf(
"end id=%d:%d %s grpc-status=%s duration=%dµs response-length=%dB%s",
ev.ResponseEnd.GetId().GetBase(),
ev.ResponseEnd.GetId().GetStream(),
flow,
codes.Code(eos.GrpcStatusCode),
ev.ResponseEnd.GetSinceResponseInit().GetNanos()/1000,
ev.ResponseEnd.GetResponseBytes(),
resources,
)
case *pb.Eos_ResetErrorCode:
return fmt.Sprintf(
"end id=%d:%d %s reset-error=%+v duration=%dµs response-length=%dB%s",
ev.ResponseEnd.GetId().GetBase(),
ev.ResponseEnd.GetId().GetStream(),
flow,
eos.ResetErrorCode,
ev.ResponseEnd.GetSinceResponseInit().GetNanos()/1000,
ev.ResponseEnd.GetResponseBytes(),
resources,
)
default:
return fmt.Sprintf("end id=%d:%d %s duration=%dµs response-length=%dB%s",
ev.ResponseEnd.GetId().GetBase(),
ev.ResponseEnd.GetId().GetStream(),
flow,
ev.ResponseEnd.GetSinceResponseInit().GetNanos()/1000,
ev.ResponseEnd.GetResponseBytes(),
resources,
)
}
default:
return fmt.Sprintf("unknown %s", flow)
}
}