forked from alexei-led/pumba
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
331 lines (307 loc) · 9.08 KB
/
main.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
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/alexei-led/pumba/pkg/chaos"
"github.com/alexei-led/pumba/pkg/chaos/docker/cmd"
netemCmd "github.com/alexei-led/pumba/pkg/chaos/netem/cmd"
stressCmd "github.com/alexei-led/pumba/pkg/chaos/stress/cmd"
"github.com/alexei-led/pumba/pkg/container"
"github.com/johntdyer/slackrus"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
var (
topContext context.Context
)
var (
// version that is passed on compile time through -ldflags
version = "local"
// commit that is passed on compile time through -ldflags
commit = "none"
// branch that is passed on compile time through -ldflags
branch = "none"
// buildTime that is passed on compile time through -ldflags
buildTime = "none"
// versionSingature is a human readable app version
versionSingature = fmt.Sprintf("%s - [%s:%.7s] %s", version, branch, commit, buildTime)
)
const (
// re2 regexp string prefix
re2Prefix = "re2:"
// default network interface
defaultInterface = "eth0"
)
func init() {
// set log level
log.SetLevel(log.WarnLevel)
log.SetFormatter(&log.TextFormatter{})
// handle termination signal
topContext = handleSignals()
}
func main() {
rootCertPath := "/etc/ssl/docker"
if os.Getenv("DOCKER_CERT_PATH") != "" {
rootCertPath = os.Getenv("DOCKER_CERT_PATH")
}
app := cli.NewApp()
app.Name = "Pumba"
app.Version = versionSingature
app.Compiled = time.Now()
app.Authors = []cli.Author{
{
Name: "Alexei Ledenev",
Email: "[email protected]",
},
}
app.EnableBashCompletion = true
app.Usage = "Pumba is a resilience testing tool, that helps applications tolerate random Docker container failures: process, network and performance."
app.ArgsUsage = fmt.Sprintf("containers (name, list of names, or RE2 regex if prefixed with %q)", re2Prefix)
app.Before = before
app.Commands = initializeCLICommands()
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "host, H",
Usage: "daemon socket to connect to",
Value: "unix:///var/run/docker.sock",
EnvVar: "DOCKER_HOST",
},
cli.BoolFlag{
Name: "tls",
Usage: "use TLS; implied by --tlsverify",
},
cli.BoolFlag{
Name: "tlsverify",
Usage: "use TLS and verify the remote",
EnvVar: "DOCKER_TLS_VERIFY",
},
cli.StringFlag{
Name: "tlscacert",
Usage: "trust certs signed only by this CA",
Value: fmt.Sprintf("%s/ca.pem", rootCertPath),
},
cli.StringFlag{
Name: "tlscert",
Usage: "client certificate for TLS authentication",
Value: fmt.Sprintf("%s/cert.pem", rootCertPath),
},
cli.StringFlag{
Name: "tlskey",
Usage: "client key for TLS authentication",
Value: fmt.Sprintf("%s/key.pem", rootCertPath),
},
cli.StringFlag{
Name: "log-level, l",
Usage: "set log level (debug, info, warning(*), error, fatal, panic)",
Value: "warning",
EnvVar: "LOG_LEVEL",
},
cli.BoolFlag{
Name: "json, j",
Usage: "produce log in JSON format: Logstash and Splunk friendly",
EnvVar: "LOG_JSON",
},
cli.StringFlag{
Name: "slackhook",
Usage: "web hook url; send Pumba log events to Slack",
},
cli.StringFlag{
Name: "slackchannel",
Usage: "Slack channel (default #pumba)",
Value: "#pumba",
},
cli.DurationFlag{
Name: "interval, i",
Usage: "recurrent interval for chaos command; use with optional unit suffix: 'ms/s/m/h'",
},
cli.StringSliceFlag{
Name: "label",
Usage: "filter containers by labels, e.g '--label key=value' (multiple labels supported)",
},
cli.BoolFlag{
Name: "random, r",
Usage: "randomly select single matching container from list of target containers",
},
cli.BoolFlag{
Name: "dry-run",
Usage: "dry run does not create chaos, only logs planned chaos commands",
EnvVar: "DRY-RUN",
},
cli.BoolFlag{
Name: "skip-error",
Usage: "skip chaos command error and retry to execute the command on next interval tick",
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func before(c *cli.Context) error {
// set debug log level
switch level := c.GlobalString("log-level"); level {
case "debug", "DEBUG":
log.SetLevel(log.DebugLevel)
case "info", "INFO":
log.SetLevel(log.InfoLevel)
case "warning", "WARNING":
log.SetLevel(log.WarnLevel)
case "error", "ERROR":
log.SetLevel(log.ErrorLevel)
case "fatal", "FATAL":
log.SetLevel(log.FatalLevel)
case "panic", "PANIC":
log.SetLevel(log.PanicLevel)
default:
log.SetLevel(log.WarnLevel)
}
// set log formatter to JSON
if c.GlobalBool("json") {
log.SetFormatter(&log.JSONFormatter{})
}
// set Slack log channel
if c.GlobalString("slackhook") != "" {
log.AddHook(&slackrus.SlackrusHook{
HookURL: c.GlobalString("slackhook"),
AcceptedLevels: slackrus.LevelThreshold(log.GetLevel()),
Channel: c.GlobalString("slackchannel"),
IconEmoji: ":boar:",
Username: "pumba_bot",
})
}
// Set-up container client
tlsCfg, err := tlsConfig(c)
if err != nil {
return err
}
// create new Docker client
chaos.DockerClient, err = container.NewClient(c.GlobalString("host"), tlsCfg)
if err != nil {
return errors.Wrap(err, "could not create Docker client")
}
return nil
}
func handleSignals() context.Context {
// Graceful shut-down on SIGINT/SIGTERM
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
// create cancelable context
ctx, cancel := context.WithCancel(context.Background())
go func() {
defer cancel()
sid := <-sig
log.Debugf("Received signal: %d\n", sid)
log.Debug("Canceling running chaos commands ...")
log.Debug("Gracefully exiting after some cleanup ...")
}()
return ctx
}
// tlsConfig translates the command-line options into a tls.Config struct
func tlsConfig(c *cli.Context) (*tls.Config, error) {
var tlsCfg *tls.Config
var err error
caCertFlag := c.GlobalString("tlscacert")
certFlag := c.GlobalString("tlscert")
keyFlag := c.GlobalString("tlskey")
if c.GlobalBool("tls") || c.GlobalBool("tlsverify") {
tlsCfg = &tls.Config{
InsecureSkipVerify: !c.GlobalBool("tlsverify"), //nolint:gosec
}
// Load CA cert
if caCertFlag != "" {
var caCert []byte
if strings.HasPrefix(caCertFlag, "/") {
caCert, err = os.ReadFile(caCertFlag)
if err != nil {
return nil, errors.Wrap(err, "unable to read CA certificate")
}
} else {
caCert = []byte(caCertFlag)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsCfg.RootCAs = caCertPool
}
// Load client certificate
if certFlag != "" && keyFlag != "" {
var cert tls.Certificate
if strings.HasPrefix(certFlag, "/") && strings.HasPrefix(keyFlag, "/") {
cert, err = tls.LoadX509KeyPair(certFlag, keyFlag)
if err != nil {
return nil, errors.Wrap(err, "unable to load client certificate")
}
} else {
cert, err = tls.X509KeyPair([]byte(certFlag), []byte(keyFlag))
if err != nil {
return nil, errors.Wrap(err, "unable to load client certificate")
}
}
tlsCfg.Certificates = []tls.Certificate{cert}
}
}
return tlsCfg, nil
}
func initializeCLICommands() []cli.Command {
return []cli.Command{
*cmd.NewKillCLICommand(topContext),
*cmd.NewExecCLICommand(topContext),
*cmd.NewRestartCLICommand(topContext),
*cmd.NewStopCLICommand(topContext),
*cmd.NewPauseCLICommand(topContext),
*cmd.NewRemoveCLICommand(topContext),
*stressCmd.NewStressCLICommand(topContext),
{
Name: "netem",
Flags: []cli.Flag{
cli.DurationFlag{
Name: "duration, d",
Usage: "network emulation duration; should be smaller than recurrent interval; use with optional unit suffix: 'ms/s/m/h'",
},
cli.StringFlag{
Name: "interface, i",
Usage: "network interface to apply delay on",
Value: defaultInterface,
},
cli.StringSliceFlag{
Name: "target, t",
Usage: "target IP filter; supports multiple IPs; supports CIDR notation",
},
cli.StringFlag{
Name: "egress-port, egressPort",
Usage: "target port filter for egress, or sport; supports multiple ports (comma-separated)",
},
cli.StringFlag{
Name: "ingress-port, ingressPort",
Usage: "target port filter for ingress, or dport; supports multiple ports (comma-separated)",
},
cli.StringFlag{
Name: "tc-image",
Usage: "Docker image with tc (iproute2 package); try 'gaiadocker/iproute2'",
},
cli.BoolTFlag{
Name: "pull-image",
Usage: "force pull tc-image",
},
},
Usage: "emulate the properties of wide area networks",
ArgsUsage: fmt.Sprintf("containers (name, list of names, or RE2 regex if prefixed with %q", re2Prefix),
Description: "delay, loss, duplicate and re-order (run 'netem') packets, and limit the bandwidth, to emulate different network problems",
Subcommands: []cli.Command{
*netemCmd.NewDelayCLICommand(topContext),
*netemCmd.NewLossCLICommand(topContext),
*netemCmd.NewLossStateCLICommand(topContext),
*netemCmd.NewLossGECLICommand(topContext),
*netemCmd.NewRateCLICommand(topContext),
*netemCmd.NewDuplicateCLICommand(topContext),
*netemCmd.NewCorruptCLICommand(topContext),
},
},
}
}