/
command.go
227 lines (190 loc) · 6.59 KB
/
command.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2018-2020 Datadog, Inc.
// Package dogstatsdreplay implements 'agent dogstatsd-replay'.
package dogstatsdreplay
import (
"context"
"crypto/tls"
"fmt"
"net"
"os"
"os/signal"
"syscall"
"go.uber.org/fx"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"github.com/DataDog/datadog-agent/cmd/agent/command"
"github.com/DataDog/datadog-agent/comp/core"
"github.com/DataDog/datadog-agent/comp/core/config"
"github.com/DataDog/datadog-agent/comp/core/log"
"github.com/DataDog/datadog-agent/comp/dogstatsd/replay"
"github.com/DataDog/datadog-agent/pkg/api/security"
pkgconfig "github.com/DataDog/datadog-agent/pkg/config"
pb "github.com/DataDog/datadog-agent/pkg/proto/pbgo/core"
"github.com/DataDog/datadog-agent/pkg/util/fxutil"
"github.com/spf13/cobra"
)
const (
defaultIterations = 1
)
// cliParams are the command-line arguments for this subcommand
type cliParams struct {
*command.GlobalParams
// subcommand-specific flags
dsdReplayFilePath string
dsdVerboseReplay bool
dsdMmapReplay bool
dsdReplayIterations int
}
// Commands returns a slice of subcommands for the 'agent' command.
func Commands(globalParams *command.GlobalParams) []*cobra.Command {
cliParams := &cliParams{
GlobalParams: globalParams,
}
dogstatsdReplayCmd := &cobra.Command{
Use: "dogstatsd-replay",
Short: "Replay dogstatsd traffic",
Long: ``,
RunE: func(cmd *cobra.Command, args []string) error {
return fxutil.OneShot(dogstatsdReplay,
fx.Supply(cliParams),
fx.Supply(command.GetDefaultCoreBundleParams(cliParams.GlobalParams)),
core.Bundle(),
)
},
}
dogstatsdReplayCmd.Flags().StringVarP(&cliParams.dsdReplayFilePath, "file", "f", "", "Input file with traffic captured with dogstatsd-capture.")
dogstatsdReplayCmd.Flags().BoolVarP(&cliParams.dsdVerboseReplay, "verbose", "v", false, "Verbose replay.")
dogstatsdReplayCmd.Flags().BoolVarP(&cliParams.dsdMmapReplay, "mmap", "m", true, "Mmap file for replay. Set to false to load the entire file into memory instead")
dogstatsdReplayCmd.Flags().IntVarP(&cliParams.dsdReplayIterations, "loops", "l", defaultIterations, "Number of iterations to replay.")
return []*cobra.Command{dogstatsdReplayCmd}
}
//nolint:revive // TODO(AML) Fix revive linter
func dogstatsdReplay(log log.Component, config config.Component, cliParams *cliParams) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// setup sig handlers
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
done <- true
}()
fmt.Printf("Replaying dogstatsd traffic...\n\n")
// TODO: refactor all the instantiation of the SecureAgentClient to a helper
token, err := security.FetchAuthToken(config)
if err != nil {
return fmt.Errorf("unable to fetch authentication token: %w", err)
}
md := metadata.MD{
"authorization": []string{fmt.Sprintf("Bearer %s", token)},
}
ctx = metadata.NewOutgoingContext(ctx, md)
// NOTE: we're using InsecureSkipVerify because the gRPC server only
// persists its TLS certs in memory, and we currently have no
// infrastructure to make them available to clients. This is NOT
// equivalent to grpc.WithInsecure(), since that assumes a non-TLS
// connection.
creds := credentials.NewTLS(&tls.Config{
InsecureSkipVerify: true,
})
apiconn, err := grpc.DialContext(
ctx,
fmt.Sprintf(":%v", pkgconfig.Datadog.GetInt("cmd_port")),
grpc.WithTransportCredentials(creds),
)
if err != nil {
return err
}
cli := pb.NewAgentSecureClient(apiconn)
depth := 10
reader, err := replay.NewTrafficCaptureReader(cliParams.dsdReplayFilePath, depth, cliParams.dsdMmapReplay)
if reader != nil {
defer reader.Close()
}
if err != nil {
fmt.Printf("could not open: %s\n", cliParams.dsdReplayFilePath)
return err
}
s := pkgconfig.Datadog.GetString("dogstatsd_socket")
if s == "" {
return fmt.Errorf("Dogstatsd UNIX socket disabled")
}
addr, err := net.ResolveUnixAddr("unixgram", s)
if err != nil {
return err
}
sk, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_DGRAM, 0)
if err != nil {
return err
}
defer syscall.Close(sk)
err = syscall.SetsockoptInt(sk, syscall.SOL_SOCKET, syscall.SO_SNDBUF,
pkgconfig.Datadog.GetInt("dogstatsd_buffer_size"))
if err != nil {
return err
}
dsdSock := os.NewFile(uintptr(sk), "dogstatsd_socket")
conn, err := net.FileConn(dsdSock)
if err != nil {
return err
}
defer conn.Close()
// let's read state before proceeding
pidmap, state, err := reader.ReadState()
if err != nil {
fmt.Printf("Unable to load state from file, tag enrichment will be unavailable for this capture: %v\n", err)
}
resp, err := cli.DogstatsdSetTaggerState(ctx, &pb.TaggerState{State: state, PidMap: pidmap})
if err != nil {
fmt.Printf("Unable to load state API error, tag enrichment will be unavailable for this capture: %v\n", err)
} else if !resp.GetLoaded() {
fmt.Printf("API refused to set the tagger state, tag enrichment will be unavailable for this capture.\n")
}
breaker := false
for i := 0; (i < cliParams.dsdReplayIterations || cliParams.dsdReplayIterations == 0) && !breaker; i++ {
// enable reading at natural rate
ready := make(chan struct{})
go reader.Read(ready)
// wait for go routine to start processing...
<-ready
replay:
for {
select {
case msg := <-reader.Traffic:
// The cadence is enforced by the reader. The reader will only write to
// the traffic channel when it estimates the payload should be submitted.
n, oobn, err := conn.(*net.UnixConn).WriteMsgUnix(
msg.Payload[:msg.PayloadSize], replay.GetUcredsForPid(msg.Pid), addr)
if err != nil {
return err
}
if cliParams.dsdVerboseReplay {
fmt.Printf("Sent Payload: %d bytes, and OOB: %d bytes\n", n, oobn)
}
case <-reader.Done:
break replay
case <-done:
breaker = true
break replay
}
}
}
fmt.Println("clearing agent replay states...")
resp, err = cli.DogstatsdSetTaggerState(ctx, &pb.TaggerState{})
if err != nil {
fmt.Printf("Unable to load state API error, tag enrichment will be unavailable for this capture: %v\n", err)
} else if resp.GetLoaded() {
fmt.Printf("The capture state and pid map have been successfully cleared from the agent\n")
}
err = reader.Shutdown()
if err != nil {
fmt.Printf("There was an issue shutting down the replay: %v\n", err)
}
fmt.Println("replay done")
return err
}