Repository navigation
Expand file tree
/
Copy pathtop.go
More file actions
774 lines (689 loc) · 18.8 KB
/
Copy pathtop.go
File metadata and controls
774 lines (689 loc) · 18.8 KB
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
package cmd
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"sort"
"strconv"
"strings"
"time"
"github.com/linkerd/linkerd2/pkg/addr"
pkgcmd "github.com/linkerd/linkerd2/pkg/cmd"
"github.com/linkerd/linkerd2/pkg/healthcheck"
"github.com/linkerd/linkerd2/pkg/k8s"
"github.com/linkerd/linkerd2/pkg/protohttp"
metricsAPI "github.com/linkerd/linkerd2/viz/metrics-api"
metricsPb "github.com/linkerd/linkerd2/viz/metrics-api/gen/viz"
"github.com/linkerd/linkerd2/viz/pkg/api"
hc "github.com/linkerd/linkerd2/viz/pkg/healthcheck"
vizutil "github.com/linkerd/linkerd2/viz/pkg/util"
tapPb "github.com/linkerd/linkerd2/viz/tap/gen/tap"
"github.com/linkerd/linkerd2/viz/tap/pkg"
runewidth "github.com/mattn/go-runewidth"
termbox "github.com/nsf/termbox-go"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"google.golang.org/grpc/codes"
)
type topOptions struct {
namespace string
toResource string
toNamespace string
maxRps float32
scheme string
method string
authority string
path string
hideSources bool
routes bool
labelSelector string
}
type topRequest struct {
event *tapPb.TapEvent
reqInit *tapPb.TapEvent_Http_RequestInit
rspInit *tapPb.TapEvent_Http_ResponseInit
rspEnd *tapPb.TapEvent_Http_ResponseEnd
}
type topRequestID struct {
src string
dst string
stream uint64
}
func (id topRequestID) String() string {
return fmt.Sprintf("%s->%s(%d)", id.src, id.dst, id.stream)
}
type tableColumn struct {
header string
width int
// Columns with key=true will be treated as the primary key for the table.
// In other words, if two rows have equal values for the key=true columns
// then those rows will be merged.
key bool
// If true, render this column.
display bool
// If true, set the width to the widest value in this column.
flexible bool
rightAlign bool
value func(tableRow) string
}
type tableRow struct {
path string
method string
route string
source string
destination string
count int
best time.Duration
worst time.Duration
last time.Duration
successes int
failures int
}
func (r tableRow) merge(other tableRow) tableRow {
r.count += other.count
if other.best.Nanoseconds() < r.best.Nanoseconds() {
r.best = other.best
}
if other.worst.Nanoseconds() > r.worst.Nanoseconds() {
r.worst = other.worst
}
r.last = other.last
r.successes += other.successes
r.failures += other.failures
return r
}
type column int
const (
sourceColumn column = iota
destinationColumn
methodColumn
pathColumn
routeColumn
countColumn
bestColumn
worstColumn
lastColumn
successRateColumn
columnCount
)
type topTable struct {
columns [columnCount]tableColumn
rows []tableRow
}
func newTopTable() *topTable {
table := topTable{}
table.columns[sourceColumn] =
tableColumn{
header: "Source",
width: 23,
key: true,
display: true,
flexible: true,
value: func(r tableRow) string {
return r.source
},
}
table.columns[destinationColumn] =
tableColumn{
header: "Destination",
width: 23,
key: true,
display: true,
flexible: true,
value: func(r tableRow) string {
return r.destination
},
}
table.columns[methodColumn] =
tableColumn{
header: "Method",
width: 10,
key: true,
display: true,
flexible: false,
value: func(r tableRow) string {
return r.method
},
}
table.columns[pathColumn] =
tableColumn{
header: "Path",
width: 37,
key: true,
display: true,
flexible: true,
value: func(r tableRow) string {
return r.path
},
}
table.columns[routeColumn] =
tableColumn{
header: "Route",
width: 47,
key: false,
display: false,
flexible: true,
value: func(r tableRow) string {
return r.route
},
}
table.columns[countColumn] =
tableColumn{
header: "Count",
width: 6,
key: false,
display: true,
flexible: false,
rightAlign: true,
value: func(r tableRow) string {
return strconv.Itoa(r.count)
},
}
table.columns[bestColumn] =
tableColumn{
header: "Best",
width: 6,
key: false,
display: true,
flexible: false,
rightAlign: true,
value: func(r tableRow) string {
return formatDuration(r.best)
},
}
table.columns[worstColumn] =
tableColumn{
header: "Worst",
width: 6,
key: false,
display: true,
flexible: false,
rightAlign: true,
value: func(r tableRow) string {
return formatDuration(r.worst)
},
}
table.columns[lastColumn] =
tableColumn{
header: "Last",
width: 6,
key: false,
display: true,
flexible: false,
rightAlign: true,
value: func(r tableRow) string {
return formatDuration(r.last)
},
}
table.columns[successRateColumn] =
tableColumn{
header: "Success Rate",
width: 12,
key: false,
display: true,
flexible: false,
rightAlign: true,
value: func(r tableRow) string {
return fmt.Sprintf("%.2f%%", 100.0*float32(r.successes)/float32(r.successes+r.failures))
},
}
return &table
}
const (
headerHeight = 4
columnSpacing = 2
xOffset = 5
)
func newTopOptions() *topOptions {
return &topOptions{
toResource: "",
toNamespace: "",
maxRps: maxRps,
scheme: "",
method: "",
authority: "",
path: "",
hideSources: false,
routes: false,
labelSelector: "",
}
}
// NewCmdTop creates a new cobra command `top` for top functionality
func NewCmdTop() *cobra.Command {
options := newTopOptions()
table := newTopTable()
cmd := &cobra.Command{
Use: "top [flags] (RESOURCE)",
Short: "Display sorted information about live traffic",
Long: `Display sorted information about live traffic.
The RESOURCE argument specifies the target resource(s) to view traffic for:
(TYPE [NAME] | TYPE/NAME)
Examples:
* cronjob/my-cronjob
* deploy
* deploy/my-deploy
* deploy my-deploy
* ds/my-daemonset
* job/my-job
* ns/my-ns
* rs
* rs/my-replicaset
* sts
* sts/my-statefulset
Valid resource types include:
* cronjobs
* daemonsets
* deployments
* jobs
* namespaces
* pods
* replicasets
* replicationcontrollers
* statefulsets
* services (only supported as a --to resource)`,
Example: ` # display traffic for the web deployment in the default namespace
linkerd viz top deploy/web
# display traffic for the web-dlbvj pod in the default namespace
linkerd viz top pod/web-dlbvj`,
Args: cobra.RangeArgs(1, 2),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
// This command requires at most two arguments if we already have
// two after requesting autocompletion i.e. [tab][tab]
// skip running validArgsFunction
if len(args) > 1 {
return nil, cobra.ShellCompDirectiveError
}
k8sAPI, err := k8s.NewAPI(kubeconfigPath, kubeContext, impersonate, impersonateGroup, 0)
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
if options.namespace == "" {
options.namespace = pkgcmd.GetDefaultNamespace(kubeconfigPath, kubeContext)
}
cc := k8s.NewCommandCompletion(k8sAPI, options.namespace)
results, err := cc.Complete(args, toComplete)
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
return results, cobra.ShellCompDirectiveDefault
},
RunE: func(cmd *cobra.Command, args []string) error {
if options.namespace == "" {
options.namespace = pkgcmd.GetDefaultNamespace(kubeconfigPath, kubeContext)
}
api.CheckClientOrExit(hc.VizOptions{
Options: &healthcheck.Options{
ControlPlaneNamespace: controlPlaneNamespace,
KubeConfig: kubeconfigPath,
Impersonate: impersonate,
ImpersonateGroup: impersonateGroup,
KubeContext: kubeContext,
APIAddr: apiAddr,
},
VizNamespaceOverride: vizNamespace,
})
requestParams := pkg.TapRequestParams{
Resource: strings.Join(args, "/"),
Namespace: options.namespace,
ToResource: options.toResource,
ToNamespace: options.toNamespace,
MaxRps: options.maxRps,
Scheme: options.scheme,
Method: options.method,
Authority: options.authority,
Path: options.path,
LabelSelector: options.labelSelector,
}
if options.hideSources {
table.columns[sourceColumn].key = false
table.columns[sourceColumn].display = false
}
if options.routes {
table.columns[methodColumn].key = false
table.columns[methodColumn].display = false
table.columns[pathColumn].key = false
table.columns[pathColumn].display = false
table.columns[routeColumn].key = true
table.columns[routeColumn].display = true
}
req, err := pkg.BuildTapByResourceRequest(requestParams)
if err != nil {
return err
}
k8sAPI, err := k8s.NewAPI(kubeconfigPath, kubeContext, impersonate, impersonateGroup, 0)
if err != nil {
return err
}
return getTrafficByResourceFromAPI(cmd.Context(), k8sAPI, req, table)
},
}
cmd.PersistentFlags().StringVarP(&options.namespace, "namespace", "n", options.namespace,
"Namespace of the specified resource")
cmd.PersistentFlags().StringVar(&options.toResource, "to", options.toResource,
"Display requests to this resource")
cmd.PersistentFlags().StringVar(&options.toNamespace, "to-namespace", options.toNamespace,
"Sets the namespace used to lookup the \"--to\" resource; by default the current \"--namespace\" is used")
cmd.PersistentFlags().Float32Var(&options.maxRps, "max-rps", options.maxRps,
"Maximum requests per second to tap.")
cmd.PersistentFlags().StringVar(&options.scheme, "scheme", options.scheme,
"Display requests with this scheme")
cmd.PersistentFlags().StringVar(&options.method, "method", options.method,
"Display requests with this HTTP method")
cmd.PersistentFlags().StringVar(&options.authority, "authority", options.authority,
"Display requests with this :authority")
cmd.PersistentFlags().StringVar(&options.path, "path", options.path,
"Display requests with paths that start with this prefix")
cmd.PersistentFlags().BoolVar(&options.hideSources, "hide-sources", options.hideSources, "Hide the source column")
cmd.PersistentFlags().BoolVar(&options.routes, "routes", options.routes, "Display data per route instead of per path")
cmd.PersistentFlags().StringVarP(&options.labelSelector, "selector", "l", options.labelSelector, "Selector (label query) to filter on, supports '=', '==', and '!='")
pkgcmd.ConfigureNamespaceFlagCompletion(
cmd, []string{"namespace", "to-namespace"},
kubeconfigPath, impersonate, impersonateGroup, kubeContext)
return cmd
}
func getTrafficByResourceFromAPI(ctx context.Context, k8sAPI *k8s.KubernetesAPI, req *tapPb.TapByResourceRequest, table *topTable) error {
reader, body, err := pkg.Reader(ctx, k8sAPI, req)
if err != nil {
return err
}
defer body.Close()
err = termbox.Init()
if err != nil {
return err
}
defer termbox.Close()
// for event processing:
// reader ->
// recvEvents() ->
// eventCh ->
// processEvents() ->
// requestCh ->
// renderTable()
eventCh := make(chan *tapPb.TapEvent)
requestCh := make(chan topRequest, 100)
// for closing:
// recvEvents() || pollInput() ->
// closing ->
// done ->
// processEvents() && renderTable()
closing := make(chan struct{}, 1)
done := make(chan struct{})
horizontalScroll := make(chan int)
go pollInput(done, horizontalScroll)
go recvEvents(reader, eventCh, closing)
go processEvents(eventCh, requestCh, done)
go func() {
<-closing
}()
renderTable(table, requestCh, done, horizontalScroll)
return nil
}
func recvEvents(tapByteStream *bufio.Reader, eventCh chan<- *tapPb.TapEvent, closing chan<- struct{}) {
for {
event := &tapPb.TapEvent{}
err := protohttp.FromByteStreamToProtocolBuffers(tapByteStream, event)
if err != nil {
if errors.Is(err, io.EOF) {
fmt.Println("Tap stream terminated")
} else if !strings.HasSuffix(err.Error(), pkg.ErrClosedResponseBody) {
fmt.Println(err.Error())
}
closing <- struct{}{}
return
}
eventCh <- event
}
}
func processEvents(eventCh <-chan *tapPb.TapEvent, requestCh chan<- topRequest, done <-chan struct{}) {
outstandingRequests := make(map[topRequestID]topRequest)
for {
select {
case <-done:
return
case event := <-eventCh:
id := topRequestID{
src: addr.PublicAddressToString(event.GetSource()),
dst: addr.PublicAddressToString(event.GetDestination()),
}
switch ev := event.GetHttp().GetEvent().(type) {
case *tapPb.TapEvent_Http_RequestInit_:
id.stream = ev.RequestInit.GetId().Stream
outstandingRequests[id] = topRequest{
event: event,
reqInit: ev.RequestInit,
}
case *tapPb.TapEvent_Http_ResponseInit_:
id.stream = ev.ResponseInit.GetId().Stream
if req, ok := outstandingRequests[id]; ok {
req.rspInit = ev.ResponseInit
outstandingRequests[id] = req
} else {
log.Warnf("Got ResponseInit for unknown stream: %s", id)
}
case *tapPb.TapEvent_Http_ResponseEnd_:
id.stream = ev.ResponseEnd.GetId().Stream
if req, ok := outstandingRequests[id]; ok {
req.rspEnd = ev.ResponseEnd
requestCh <- req
} else {
log.Warnf("Got ResponseEnd for unknown stream: %s", id)
}
}
}
}
}
func pollInput(done chan<- struct{}, horizontalScroll chan int) {
for {
switch ev := termbox.PollEvent(); ev.Type {
case termbox.EventKey:
if ev.Ch == 'q' || ev.Key == termbox.KeyCtrlC {
close(done)
return
}
if ev.Ch == 'a' || ev.Key == termbox.KeyArrowLeft {
horizontalScroll <- xOffset
}
if ev.Ch == 'd' || ev.Key == termbox.KeyArrowRight {
horizontalScroll <- -xOffset
}
}
}
}
func renderTable(table *topTable, requestCh <-chan topRequest, done <-chan struct{}, horizontalScroll chan int) {
scrollpos := 0
ticker := time.NewTicker(100 * time.Millisecond)
width, _ := termbox.Size()
tablewidth := table.tableWidthCalc()
for {
select {
case <-done:
return
case req := <-requestCh:
table.insert(req)
case <-ticker.C:
termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
width, _ = termbox.Size()
table.adjustColumnWidths()
tablewidth = table.tableWidthCalc()
table.renderHeaders(scrollpos)
table.renderBody(scrollpos)
termbox.Flush()
case offset := <-horizontalScroll:
if (offset > 0 && scrollpos < 0) || (offset < 0 && scrollpos > (width-tablewidth)) {
scrollpos += offset
}
}
}
}
func newRow(req topRequest) (tableRow, error) {
path := req.reqInit.GetPath()
route := req.event.GetRouteMeta().GetLabels()["route"]
if route == "" {
route = metricsAPI.DefaultRouteName
}
source := stripPort(addr.PublicAddressToString(req.event.GetSource()))
if pod := req.event.SourceMeta.Labels["pod"]; pod != "" {
source = pod
}
destination := stripPort(addr.PublicAddressToString(req.event.GetDestination()))
if pod := req.event.DestinationMeta.Labels["pod"]; pod != "" {
destination = pod
}
err := req.rspEnd.GetSinceRequestInit().CheckValid()
if err != nil {
return tableRow{}, fmt.Errorf("error parsing duration %v: %w", req.rspEnd.GetSinceRequestInit(), err)
}
latency := req.rspEnd.GetSinceRequestInit().AsDuration()
// TODO: Once tap events have a classification field, we should use that field
// instead of determining success here.
success := req.rspInit.GetHttpStatus() < 500
if success {
switch eos := req.rspEnd.GetEos().GetEnd().(type) {
case *metricsPb.Eos_GrpcStatusCode:
switch codes.Code(eos.GrpcStatusCode) {
case codes.Unknown,
codes.DeadlineExceeded,
codes.Internal,
codes.Unavailable,
codes.DataLoss:
success = false
default:
success = true
}
case *metricsPb.Eos_ResetErrorCode:
success = false
}
}
successes := 0
failures := 0
if success {
successes = 1
} else {
failures = 1
}
return tableRow{
path: path,
method: vizutil.HTTPMethodToString(req.reqInit.GetMethod()),
route: route,
source: source,
destination: destination,
best: latency,
worst: latency,
last: latency,
count: 1,
successes: successes,
failures: failures,
}, nil
}
func (t *topTable) insert(req topRequest) {
insert, err := newRow(req)
if err != nil {
log.Error(err.Error())
return
}
found := false
// Search for a matching row
for i, row := range t.rows {
match := true
// If the rows have equal values in all of the key columns, merge them.
for _, col := range t.columns {
if col.key {
if col.value(row) != col.value(insert) {
match = false
break
}
}
}
if match {
found = true
t.rows[i] = t.rows[i].merge(insert)
break
}
}
if !found {
t.rows = append(t.rows, insert)
}
}
func stripPort(address string) string {
return strings.Split(address, ":")[0]
}
func (t *topTable) renderHeaders(scrollpos int) {
tbprint(0, 0, "(press q to quit)")
tbprint(0, 1, "(press a/LeftArrowKey to scroll left, d/RightArrowKey to scroll right)")
x := scrollpos
for _, col := range t.columns {
if !col.display {
continue
}
padding := 0
if col.rightAlign {
padding = col.width - runewidth.StringWidth(col.header)
}
tbprintBold(x+padding, headerHeight-1, col.header)
x += col.width + columnSpacing
}
}
func (t *topTable) tableWidthCalc() int {
tablewidth := 0
for i := range t.columns {
tablewidth = tablewidth + t.columns[i].width + columnSpacing
}
return tablewidth - columnSpacing
}
func (t *topTable) adjustColumnWidths() {
for i, col := range t.columns {
if !col.flexible {
continue
}
t.columns[i].width = runewidth.StringWidth(col.header)
for _, row := range t.rows {
cellWidth := runewidth.StringWidth(col.value(row))
if cellWidth > t.columns[i].width {
t.columns[i].width = cellWidth
}
}
}
}
func (t *topTable) renderBody(scrollpos int) {
sort.SliceStable(t.rows, func(i, j int) bool {
return t.rows[i].count > t.rows[j].count
})
for i, row := range t.rows {
x := scrollpos
for _, col := range t.columns {
if !col.display {
continue
}
value := col.value(row)
padding := 0
if col.rightAlign {
padding = col.width - runewidth.StringWidth(value)
}
tbprint(x+padding, i+headerHeight, value)
x += col.width + columnSpacing
}
}
}
func tbprint(x, y int, msg string) {
for _, c := range msg {
termbox.SetCell(x, y, c, termbox.ColorDefault, termbox.ColorDefault)
x += runewidth.RuneWidth(c)
}
}
func tbprintBold(x, y int, msg string) {
for _, c := range msg {
termbox.SetCell(x, y, c, termbox.AttrBold, termbox.ColorDefault)
x += runewidth.RuneWidth(c)
}
}
func formatDuration(d time.Duration) string {
if d < time.Millisecond {
return d.Round(time.Microsecond).String()
}
if d < time.Second {
return d.Round(time.Millisecond).String()
}
return d.Round(time.Second).String()
}