-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtapshark.go
382 lines (327 loc) · 11.7 KB
/
tapshark.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
package cmd
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/adleong/tapshark/pkg"
"github.com/gdamore/tcell/v2"
"github.com/golang/protobuf/ptypes"
"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/viz/pkg/util"
"github.com/linkerd/linkerd2/viz/pkg/api"
tapPb "github.com/linkerd/linkerd2/viz/tap/gen/tap"
tapPkg "github.com/linkerd/linkerd2/viz/tap/pkg"
"github.com/rivo/tview"
"github.com/spf13/cobra"
)
const defaultLinkerdNamespace = "linkerd"
type (
eventLog struct {
app *tview.Application
table *tview.Table
details *tview.TextView
events []pkg.Stream
}
options struct {
apiAddr string // An empty value means "use the Kubernetes configuration"
controlPlaneNamespace string
kubeconfigPath string
kubeContext string
impersonate string
impersonateGroup []string
namespace string
toResource string
toNamespace string
maxRps float32
scheme string
method string
authority string
path string
labelSelector string
}
)
// NewCmdTapShark creates a new cobra command `tap` for tap functionality
func NewCmdTapShark() *cobra.Command {
options := options{}
cmd := &cobra.Command{
Use: "tapshark [flags] (RESOURCE)",
Short: "Listen to a traffic stream",
Long: `Listen to a traffic stream.
The RESOURCE argument specifies the target resource(s) to tap:
(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: ` # tap the web deployment in the default namespace
linkerd tapshark deploy/web
# tap the web-dlbvj pod in the default namespace
linkerd tapshark pod/web-dlbvj
# tap the test namespace, filter by request to prod namespace
linkerd tapshark ns/test --to ns/prod`,
Args: cobra.RangeArgs(1, 2),
ValidArgs: util.ValidTargets,
RunE: func(cmd *cobra.Command, args []string) error {
if options.namespace == "" {
options.namespace = pkgcmd.GetDefaultNamespace(options.kubeconfigPath, options.kubeContext)
}
api.CheckClientOrExit(healthcheck.Options{
ControlPlaneNamespace: options.controlPlaneNamespace,
KubeConfig: options.kubeconfigPath,
Impersonate: options.impersonate,
ImpersonateGroup: options.impersonateGroup,
KubeContext: options.kubeContext,
APIAddr: options.apiAddr,
})
requestParams := tapPkg.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,
Extract: true,
LabelSelector: options.labelSelector,
}
req, err := tapPkg.BuildTapByResourceRequest(requestParams)
if err != nil {
fmt.Fprint(os.Stderr, err.Error())
os.Exit(1)
}
k8sAPI, err := k8s.NewAPI(options.kubeconfigPath, options.kubeContext, options.impersonate, options.impersonateGroup, 0)
if err != nil {
fmt.Fprint(os.Stderr, err.Error())
os.Exit(1)
}
headers := []string{"TIME", pad("FROM"), pad("POD"), pad("TO"), pad("VERB"), pad("PATH"), pad("STATUS"), "LATENCY"}
table := tview.NewTable().SetFixed(1, 0).SetSelectable(true, false)
for i, header := range headers {
cell := tview.NewTableCell(header)
cell.SetAttributes(tcell.AttrBold)
table.SetCell(0, i, cell)
}
done := make(chan struct{})
details := tview.NewTextView().SetDynamicColors(true)
grid := tview.NewGrid().SetSize(2, 1, -1, -1).
AddItem(table, 0, 0, 1, 1, 0, 0, true).
AddItem(details, 1, 0, 1, 1, 0, 0, false).
SetBorders(true)
grid.SetTitle(strings.Join(os.Args, " "))
app := tview.NewApplication().SetRoot(grid, true)
app.SetInputCapture(
func(event *tcell.EventKey) *tcell.EventKey {
if event.Key() == tcell.KeyTAB {
if table.HasFocus() {
app.SetFocus(details)
} else {
app.SetFocus(table)
}
return nil
}
return event
})
eventLog := &eventLog{
app: app,
details: details,
table: table,
events: []pkg.Stream{},
}
table.SetSelectedFunc(eventLog.selectionChanged)
go eventLog.processTapEvents(cmd.Context(), k8sAPI, req, done)
if err := app.Run(); err != nil {
panic(err)
}
done <- struct{}{}
return nil
},
}
cmd.Flags().StringVarP(&options.controlPlaneNamespace, "linkerd-namespace", "L", defaultLinkerdNamespace, "Namespace in which Linkerd is installed")
cmd.Flags().StringVar(&options.kubeconfigPath, "kubeconfig", "", "Path to the kubeconfig file to use for CLI requests")
cmd.Flags().StringVar(&options.kubeContext, "context", "", "Name of the kubeconfig context to use")
cmd.Flags().StringVar(&options.impersonate, "as", "", "Username to impersonate for Kubernetes operations")
cmd.Flags().StringArrayVar(&options.impersonateGroup, "as-group", []string{}, "Group to impersonate for Kubernetes operations")
cmd.Flags().StringVar(&options.apiAddr, "api-addr", "", "Override kubeconfig and communicate directly with the control plane at host:port (mostly for testing)")
cmd.Flags().StringVarP(&options.namespace, "namespace", "n", options.namespace,
"Namespace of the specified resource")
cmd.Flags().StringVar(&options.toResource, "to", options.toResource,
"Display requests to this resource")
cmd.Flags().StringVar(&options.toNamespace, "to-namespace", options.toNamespace,
"Sets the namespace used to lookup the \"--to\" resource; by default the current \"--namespace\" is used")
cmd.Flags().Float32Var(&options.maxRps, "max-rps", options.maxRps,
"Maximum requests per second to pkg.")
cmd.Flags().StringVar(&options.scheme, "scheme", options.scheme,
"Display requests with this scheme")
cmd.Flags().StringVar(&options.method, "method", options.method,
"Display requests with this HTTP method")
cmd.Flags().StringVar(&options.authority, "authority", options.authority,
"Display requests with this :authority")
cmd.Flags().StringVar(&options.path, "path", options.path,
"Display requests with paths that start with this prefix")
cmd.Flags().StringVarP(&options.labelSelector, "selector", "l", options.labelSelector,
"Selector (label query) to filter on, supports '=', '==', and '!='")
return cmd
}
func (el *eventLog) processTapEvents(ctx context.Context, k8sAPI *k8s.KubernetesAPI, req *tapPb.TapByResourceRequest, done <-chan struct{}) {
reader, body, err := tapPkg.Reader(ctx, k8sAPI, req)
if err != nil {
fmt.Fprint(os.Stderr, err.Error())
return
}
defer body.Close()
eventCh := make(chan *tapPb.TapEvent)
requestCh := make(chan pkg.Stream, 100)
closing := make(chan struct{}, 1)
go pkg.RecvEvents(reader, eventCh, closing)
go pkg.ProcessEvents(eventCh, requestCh, done)
go func() {
<-closing
}()
start := time.Now()
for {
select {
case <-done:
return
case req := <-requestCh:
delta := time.Since(start)
req.TimestampMs = uint64(delta.Milliseconds())
el.events = append(el.events, req)
row := len(el.events)
timestamp := fmt.Sprintf("%.3f", float64(req.TimestampMs)/1000.0)
from, pod, to := fromPodTo(req)
verb := req.ReqInit.GetMethod().GetRegistered().String()
path := req.ReqInit.GetPath()
status := fmt.Sprintf("%d", req.RspInit.GetHttpStatus())
latency := latency(req)
el.app.QueueUpdateDraw(func() {
el.table.SetCellSimple(row, 0, timestamp)
el.table.SetCellSimple(row, 1, pad(from))
el.table.SetCellSimple(row, 2, pad(pod))
el.table.SetCellSimple(row, 3, pad(to))
el.table.SetCellSimple(row, 4, pad(verb))
el.table.SetCellSimple(row, 5, pad(path))
el.table.SetCellSimple(row, 6, pad(status))
el.table.SetCellSimple(row, 7, latency)
})
}
}
}
func (el *eventLog) selectionChanged(row, column int) {
if row == 0 {
el.details.Clear()
return
}
req := el.events[row-1]
from, pod, to := fromPodTo(req)
el.details.Clear()
fieldTemplate := "[::b]%s:[-:-:-] %s\n"
fmt.Fprintf(el.details, fieldTemplate, "Pod", pod)
if from != "" {
fmt.Fprintf(el.details, fieldTemplate, "From", from)
}
if to != "" {
fmt.Fprintf(el.details, fieldTemplate, "To", to)
}
fmt.Fprintln(el.details)
fmt.Fprintf(el.details, fieldTemplate, "Source", addr.PublicAddressToString(req.Event.GetSource()))
fmt.Fprintf(el.details, fieldTemplate, "Source Metadata", "")
for k, v := range req.Event.GetSourceMeta().GetLabels() {
fmt.Fprintf(el.details, "\t%s: %s\n", k, v)
}
fmt.Fprintf(el.details, fieldTemplate, "Destination", addr.PublicAddressToString(req.Event.GetDestination()))
fmt.Fprintf(el.details, fieldTemplate, "Destination Metadata", "")
for k, v := range req.Event.GetDestinationMeta().GetLabels() {
fmt.Fprintf(el.details, "\t%s: %s\n", k, v)
}
fmt.Fprintln(el.details)
if len(req.Event.GetRouteMeta().GetLabels()) > 0 {
fmt.Fprintf(el.details, fieldTemplate, "Route Metadata", "")
for k, v := range req.Event.GetRouteMeta().GetLabels() {
fmt.Fprintf(el.details, "\t%s: %s\n", k, v)
}
fmt.Fprintln(el.details)
}
fmt.Fprintf(el.details, fieldTemplate, "Scheme", req.ReqInit.GetScheme().GetRegistered().String())
fmt.Fprintf(el.details, fieldTemplate, "Verb", req.ReqInit.GetMethod().GetRegistered().String())
fmt.Fprintf(el.details, fieldTemplate, "Path", req.ReqInit.GetPath())
fmt.Fprintf(el.details, fieldTemplate, "Authority", req.ReqInit.GetAuthority())
fmt.Fprintf(el.details, fieldTemplate, "Request Headers", "")
for _, header := range req.ReqInit.GetHeaders().GetHeaders() {
fmt.Fprintf(el.details, "\t%s: %s\n", header.GetName(), header.GetValueStr())
}
fmt.Fprintf(el.details, fieldTemplate, "Latency", latency(req))
fmt.Fprintf(el.details, fieldTemplate, "Status", fmt.Sprintf("%d", req.RspInit.GetHttpStatus()))
var duration string
d, err := ptypes.Duration(req.RspEnd.GetSinceResponseInit())
if err == nil {
duration = d.String()
}
fmt.Fprintf(el.details, fieldTemplate, "Duration", duration)
fmt.Fprintf(el.details, fieldTemplate, "Response Headers", "")
for _, header := range req.RspInit.GetHeaders().GetHeaders() {
fmt.Fprintf(el.details, "\t%s: %s\n", header.GetName(), header.GetValueStr())
}
fmt.Fprintf(el.details, fieldTemplate, "Response Trailers", "")
for _, header := range req.RspEnd.Trailers.GetHeaders() {
fmt.Fprintf(el.details, "\t%s: %s\n", header.GetName(), header.GetValueStr())
}
el.details.ScrollToBeginning()
}
func pad(s string) string {
return fmt.Sprintf(" %s ", s)
}
func fromPodTo(req pkg.Stream) (string, string, string) {
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
}
var from, pod, to string
if req.Event.GetProxyDirection() == tapPb.TapEvent_INBOUND {
from = source
pod = destination
} else if req.Event.GetProxyDirection() == tapPb.TapEvent_OUTBOUND {
pod = source
to = destination
}
return from, pod, to
}
func latency(req pkg.Stream) string {
latency, err := ptypes.Duration(req.RspEnd.GetSinceRequestInit())
if err != nil {
return ""
}
return latency.String()
}
func stripPort(address string) string {
return strings.Split(address, ":")[0]
}